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:
[test1] test-1 ansible_ssh_host=abc.def.ghi.jkl ansible_ssh_port=1212 [test2] test2-1 ansible_ssh_host=abc.def.ghi.mno ansible_ssh_port=1212 [test3] test3-1 ansible_ssh_host=abc.def.ghi.pqr ansible_ssh_port=1212 test3-2 ansible_ssh_host=abc.def.ghi.stu ansible_ssh_port=1212 [all:children] test1 test2 test3
I have tried accessing the role in the following fashions:
{{ hostvars.ansible_ssh_host }}
and
{{ hostvars.test1.ansible_ssh_host }}
I get this error:
fatal: [localhost]: FAILED! => {"failed": true, "msg": "'ansible.vars.hostvars.HostVars object' has no attribute 'ansible'"}
To try this playbook on servers from your inventory file, run ansible-playbook with the same connection arguments you've used before when running our first example. Again, we'll be using an inventory file named inventory and the sammy user to connect to the remote servers: ansible-playbook -i inventory playbook-02.
To define a variable in a playbook, simply use the keyword vars before writing your variables with indentation. To access the value of the variable, place it between the double curly braces enclosed with quotation marks. In the above playbook, the greeting variable is substituted by the value Hello world!
You can use the option --list-hosts. It will show all the host IPs from your inventory file.
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 }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With