Manish Bansal
Manish Bansal

Reputation: 185

Read custom variable from ansible Host File in playbook

I am trying to read some custom variables created in Ansible host file, but i am not able to read it somehow and it is throwing exception

Hostfile

[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}} 

I couldn't find any document which is talking clearly how to read host variable

When i am running above I am getting below error.

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"}

Upvotes: 0

Views: 1820

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68024

Q: "How to read host variable?"

A: Simply reference the variable

    - command: echo {{ uname }} 


For example the inventory and the playbook below

shell> cat hosts
[webserver]
test_01     uname=abc123
test_02     uname=pqr456
shell> cat playbook.yml 
- hosts: all
  tasks:
    - debug:
        var: uname

give (abridged)

shell> ansible-playbook -i hosts playbook.yml

ok: [test_01] => 
  uname: abc123
ok: [test_02] => 
  uname: pqr456


Use hostvars to reference variables registered with other hosts. For example

shell> cat playbook.yml 
- hosts: localhost
  tasks:
    - debug:
        var: hostvars[item].uname
      loop: "{{ groups.webserver }}"

gives (abridged)

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


Notes

"... it may be better to use the command module instead ..."

Upvotes: 4

Related Questions