例如下面的清单和剧本
使用hostvar引用向其他主机注册的变量。例如
笔记
>我正在尝试读取在 Ansible 主机文件中创建的一些自定义变量,但我无法以某种方式读取它,并且它抛出了异常
主机文件
[webserver]
xx.xx.45.12 uname=abc123
xx.xx.45.13 uname=pqr456
剧本 亚姆
- name: sample playbook
hosts: all
tasks:
- name: sample echo command
shell:
cmd: echo {{hostvars['all'].uname}}
我找不到任何清楚地谈论如何读取主机变量的文档
当我在上面运行时,我得到下面的错误。
fatal: [xx.xx.45.12]: FAILED! => {"msg": "The task includes an option with an undefined variable.
The error was: "hostvars['webserver']" is undefinednnThe error appears to be in
'/mnt/c/Users/ManishBansal/Documents/work/MSS/scripts/run.yaml': line 6, column 7, but maynbe elsewhere
in the file depending on the exact syntax problem.nnThe offending line appears to be:nn tasks:n
- name: This command will get file listn ^ heren"}
问:">如何读取主机变量?
答:只需引用变量
- command: echo {{ uname }}
例如下面的清单和剧本
shell> cat hosts
[webserver]
test_01 uname=abc123
test_02 uname=pqr456
shell> cat playbook.yml
- hosts: all
tasks:
- debug:
var: uname
给予(删节(
shell> ansible-playbook -i hosts playbook.yml
ok: [test_01] =>
uname: abc123
ok: [test_02] =>
uname: pqr456
使用hostvar引用向其他主机注册的变量。例如
shell> cat playbook.yml
- hosts: localhost
tasks:
- debug:
var: hostvars[item].uname
loop: "{{ groups.webserver }}"
给予(删节(
shell> ansible-playbook -i hosts playbook.yml
ok: [localhost] => (item=test_01) =>
ansible_loop_var: item
hostvars[item].uname: abc123
item: test_01
ok: [localhost] => (item=test_02) =>
ansible_loop_var: item
hostvars[item].uname: pqr456
item: test_02
笔记
查看缓存事实
引用模块外壳注释
"...最好改用命令模块...">