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.confThen, 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 %}Written by Michael DeHaan
Related protips
2 Responses
 
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
 #Ansible 
Authors
 
Misha Behersky
79.79K
 
tartansandal
73.67K
Related Tags
#ansible
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#

 
