Storing IP address of First node (Control Node) in variable

23 views
Skip to first unread message

Homayoun Najafizadeh

unread,
Jul 26, 2017, 4:11:25 PM7/26/17
to Ansible Project
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.

Pshem Kowalczyk

unread,
Jul 26, 2017, 7:05:13 PM7/26/17
to Ansible Project
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



--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
To post to this group, send email to ansible...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/e5dd318a-ee88-4d29-a12c-12cbc1ea3810%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages