Ansible – Iterate over a host group and find IP address of each host

If you fully automate an IT infrastructure you sometimes need the individual IP addresses of each host of an host group. For example when you configure a loadbalancer or a reverse proxy and need to enter the IP addresses of the group of webservers when you cannot rely on DNS names.

The following Ansible playbook delegates the gather_facts to those webservers and iterates over their IP addresses.

---
- hosts: loadbalancers

  tasks:

    - name: delegate update_facts
      setup:
      delegate_to: '{{ item }}'
      delegate_facts: yes      
      with_items: '{{ groups["linux_webservers"] }}'
      when: hostvars[item]["ansible_default_ipv4"]["address"] is not defined

    - name: print ansible_all_ipv4_addresses
      debug:
        msg: '{{ hostvars[item]["ansible_hostname"]}}: {{ hostvars[item]["ansible_default_ipv4"]["address"] }}'
      with_items: '{{ groups["linux_webservers"] }}'
 

Sample Inventory

[loadbalancers]
lb01

[linux_webservers]
web01
web02
web03