Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple groups when iterating in a template file

This article from Ansible.com shows how you can iterate over a group inside of 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 beautifully, but the servers I want to iterate over are defined by being in multiple groups. So imagine that I want to iterate over all of the servers that are in BOTH the db_servers and qa groups. How can I do this?

I tried to specify the intersection of the group in the same manner I do in my playbook, but that doesn't work. So, when I try:

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

I get 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?

like image 449
Lee Fox Avatar asked Aug 07 '15 15:08

Lee Fox


1 Answers

Ansible has the intersect filter. See Set Theory Filters.

{% for host in groups['db_servers'] | intersect(groups['qa']) %}
   {{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}
{% endfor %}
like image 72
udondan Avatar answered Nov 02 '22 12:11

udondan