It might be a dumb question but I can’t get this to work. I want to print IP address of my control node in all nodes.
Lets say I have this in hosts:
[webservers]
10.10.10.1
10.10.10.2
10.10.10.3
When I run my “ansible-playbook -s myCode.yml” on 10.10.10.1 I want to see my debug line says:
ok: [10.10.10.1] => var = 10.10.10.1
ok: [10.10.10.2] => var = 10.10.10.1
ok: [10.10.10.3] => var = 10.10.10.1
I have done something like this but didn’t work:
- set_fact:
myIP: “{{ ansible_all_ipv4_addresses.split[0] }}”
when: inventory_hostname == groups[“serserver”][0]
This actually prints: 10.10.10.1 10.10.10.2 10.10.10.3
Thanks in advance.
Ansible runs an implicit loop for all the devices. If you access a variable in the ‘regular’ way you can only see variabels/facts set for the current device. Variables/facts set for other devices (that the loop already ran through) can be accessed via the ‘hostvars’ variable.
If you know that you want the IP of the first host in the group you might try something like this (not tested):
- set fact:
my_IP: “{{ hostvars[hostvars[hostvars.keys()[0]][‘groups’][‘webservers’][0]][‘ansible_facts’][‘ansible_default_ipv4’]['address] }}”
how this (should) work:
hostvars.keys()[0] - gets you the name of the first device in the inventory (for this play), all devices share group info
[‘groups’][‘webservers’][0] - gets you the name of the first host in that group
so this turns in to
hostvars[‘10.10.10.1’][‘ansible_facts’][‘ansible_default_ipv4’][‘address’]
which should contain the info you’re after.
There are probably some simpler ways of achieving that as well.
kind regards
Pshem