Accessing Inventory Host Variable In Ansible Playbook


Answer :

You are on the right track about hostvars.
This magic variable is used to access information about other hosts.

hostvars is a hash with inventory hostnames as keys.
To access fields of each host, use hostvars['test-1'], hostvars['test2-1'], etc.

ansible_ssh_host is deprecated in favor of ansible_host since 2.0.
So you should first remove "_ssh" from inventory hosts arguments (i.e. to become "ansible_user", "ansible_host", and "ansible_port"), then in your role call it with:

{{ hostvars['your_host_group'].ansible_host }} 

[host_group] host-1 ansible_ssh_host=192.168.0.21 node_name=foo host-2 ansible_ssh_host=192.168.0.22 node_name=bar  [host_group:vars] custom_var=asdasdasd 

You can access host group vars using:

{{ hostvars['host_group'].custom_var }} 

If you need a specific value from specific host, you can use:

{{ hostvars[groups['host_group'][0]].node_name }} 

You should be able to use the variable name directly

ansible_ssh_host 

Or you can go through hostvars without having to specify the host literally by using the magic variable inventory_hostname

hostvars[inventory_hostname].ansible_ssh_host 

Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?