Multiple groups when iterating in a template file

This article from Ansible.com shows how you can iterate over a group inside a template file: https://support.ansible.com/hc/en-us/articles/201957887-How-to-loop-over-a-list- of-hosts-in-a-group-inside-of-a-template-

It shows the following code:

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

      

It works nicely, but the servers I want to iterate over are determined by being in multiple groups. So imagine that I want to iterate over all the servers in BATH, the db_servers and qa groups. How can i do this?

I tried to indicate the intersection of the group in the same way as in my book, but it doesn't work. So when I try:

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

      

I am getting the following error:

fatal: [54.173.247.115] => {'msg': "AnsibleUndefinedVariable: One or more undefined variables: 'dict object' has no attribute 'db_servers:&qa'", 'failed': True}

      

Any suggestions on how to iterate over multiple groups in a template file?

+3


source to share


2 answers


Ansible has a filter intersect

. See Install Filter Filters .



{% for host in groups['db_servers'] | intersect(groups['qa']) %}
   {{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}
{% endfor %}

      

+3


source


You can wrap your loop in another for two server groups:



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

      

0


source







All Articles