简体   繁体   中英

Ansible gather IPs of nodes in cluster

Here is a simple cluster inventory:

[cluster]
host1
host2 
host3

Each host has an interface configured with ipv4 address. This information could be gathered with setup module and will be in ansible_facts.ansible_{{ interface }}.ipv4.address .

How do to get IPv4 addresses for interface from each individual host and make them available to each host in cluster so that each host knows all cluster IPs?

How this could be implemented in a role?

As @larsks already commented, the information is available in hostvars. If you, for example, want to print all cluster IPs you'd iterate over groups['cluster'] :

- name: Print IP addresses
  debug:
    var: hostvars[item]['ansible_eth0']['ipv4']['address']
  with_items: "{{ groups['cluster'] }}"

Note that you'll need to gather the facts first to populate hostvars for the cluster hosts. Make sure you have the following in the play where you call the task (or in the role where you have the task):

- name: A play
  hosts: cluster
  gather_facts: yes

After searching for a while on how to make list variables with Jinja2. Here is complete solution that requires cluster_interface variable and pings all nodes in cluster to check connectivity:

---
- name: gather facts about {{ cluster_interface }}
  setup:
    filter: "ansible_{{ cluster_interface }}"
  delegate_to: "{{ item }}"
  delegate_facts: True
  with_items: "{{ ansible_play_hosts }}"
  when: hostvars[item]['ansible_' + cluster_interface] is not defined

- name: cluster nodes IP addresses
  set_fact:
    cluster_nodes_ips: "{{ cluster_nodes_ips|default([]) + [hostvars[item]['ansible_' + cluster_interface]['ipv4']['address']] }}"
  with_items: "{{ ansible_play_hosts }}"

- name: current cluster node IP address
  set_fact:
    cluster_current_node_ip: "{{ hostvars[inventory_hostname]['ansible_' + cluster_interface]['ipv4']['address'] }}"

- name: ping all cluster nodes
  command: ping -c 1 {{ item }}
  with_items: "{{ cluster_nodes_ips }}"
  changed_when: false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM