Chinthaka Hasakelum
Chinthaka Hasakelum

Reputation: 171

How to get all the node list IP addresses?

In my case, there are four nodes which runs ansible. I want to get each and every node ip address. Therefore i tried these.

In my playbook.yml

- name: Ansible hosts: all gather_facts: true vars: ansible_ec2_local_ipv4: "{{ ansible_default_ipv4.address }}" roles: - role: "ansible-mongo/roles/mongo" - role: "ansible-mongo/roles/replication"

In my main.yml

        - name: ensure file exists
          copy:
            content: ""
            dest: /tmp/myconfig.cfg
            force: no
            group: "{{ mongodb_group }}"
            owner: "{{ mongodb_user }}"
            mode: 0555


        - name: Create List of nodes to be added into Cluster
          set_fact: nodelist={%for host in groups['all']%}"{{hostvars[host].ansible_eth0.ipv4.address}}"{% if not loop.last %},{% endif %}{% endfor %}

        - debug: msg=[{{nodelist}}]

        - name: Set Cluster node list in config file
          lineinfile:
            path: "/tmp/myconfig.cfg"
            line: "hosts: [{{ nodelist }}]"

But as a result when i tried to view /tmp/myconfig.cfg file. I only get one IP.

 cat /tmp/myconfig.cfg 
 hosts: ["10.1.49.149"]

Any idea on this?

Upvotes: 1

Views: 1673

Answers (2)

Mostafa Ghadimi
Mostafa Ghadimi

Reputation: 6736

Make sure you have added gather_facts: true and then the IPs are accessible using the ansible_all_ipv4_addresses variable.

Upvotes: 0

clockworknet
clockworknet

Reputation: 3056

Your set_fact loop is overwriting the value of 'nodelist' on each pass, effectively meaning you only ever end up with the last element in the loop. Try this:

- set_fact:
    nodelist: "{{ ( nodelist | default([]) ) + [ hostvars[item].ansible_eth0.ipv4.address ] }}"
  loop: "{{ groups['all'] }}"
- debug:
    var: nodelist | join(',')
  • (nodelist | default([])) outputs the current value of 'nodelist' or an empty list if it is not set (first pass)
  • + [] merges the existing list with a new list, containing a single element - the IP of the host

So 'nodelist' ultimately ends up containing a list of IP's. You can then use | join(',') to turn that into a CSV.

Upvotes: 1

Related Questions