Last Updated: May 28, 2021
·
20.78K
· mpdehaan

In a template, get all the IPs of all machines in a group

Assume that you are using the 'template' module in Ansible and have an application that needs to list out all the IP addresses of machines in another group.

First, make sure your host is talked to in a previous play:

- hosts:  db_servers
  tasks:
    - # doesn't matter what you do, just that they were talked to previously.

Then, you have your play that calls the template, as part of the same playbook (or included from the same master playbook):

- hosts: app_servers
  tasks:
    - template: src=foo/test.j2 dest=/etc/foo.conf

Then, in the template (test.j2), you can give the app servers the IP addresses of all the database servers just like this:

{% for host in groups['db_servers'] %}
   {{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}
{% endfor %}

2 Responses
Add your response

thx - it's nice for setting the bind-ip address

over 1 year ago ·

Thank you! You saved-me a lot of hours!

over 1 year ago ·