我正在尝试读取在Ansible主机文件中创建的一些自定义变量,但是我无法以某种方式读取它,并且会引发异常
主机文件
[webserver]
xx.xx.45.12 uname=abc123
xx.xx.45.13 uname=pqr456
Playbook Yaml
- 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 undefined\n\nThe error appears to be in
'/mnt/c/Users/ManishBansal/Documents/work/MSS/scripts/run.yaml': line 6, column 7, but may\nbe elsewhere
in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n tasks:\n
- name: This command will get file list\n ^ here\n"}
答案 0 :(得分:3)
问:“如何读取主机变量?”
A:只需引用变量
- 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
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
“ ...最好改用命令模块...”