Accessing inventory host variable in Ansible playbook

Question:

In Ansible 2.1, I have a role being called by a playbook that needs access to a host file variable. Any thoughts on how to access it?

I am trying to access the ansible_ssh_host in the test1 section of the following inventory host file:

I have tried accessing the role in the following fashions:

and

I get this error:

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:

Leave a Reply