从剧本的ansible主机文件中读取自定义变量

时间:2020-06-18 17:51:10

标签: ansible

我正在尝试读取在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"}

1 个答案:

答案 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


使用 hostvars 引用在其他主机上注册的变量。例如

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


笔记

“ ...最好改用命令模块...”