hopefully quick question about jinja2 for loops and variables

Hi all,

I am trying to iterate over a set of hosts in a jinja2 template almost exactly like this example from the Advanced Playbooks page:

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

the difference is in my example the group name is generated from a variable. So instead of a known string like ‘app_servers’ I have something like ‘app_type_$foo’. This syntax is not working and I never enter the for loop.

For debugging purposes I am creating a jinja2 variable

{% set group_name = app_type_{{ foo }}’ %}

and this is being set correctly, but I can’t figure out the syntax for referencing the variable I have set in the jinja2 for loop, which is likely a side affect of my Python !awesomeness

{% for host in groups[ ‘group_name’ ] %} doesn’t work, nor does

{% for host in groups[ group_name ] %}

I am hoping that this is possible, but I have a syntax issue.
any help would be most appreciated.

cheers,
Jonathan

I am not sure your set statement is right actually.

Instead of:

{% set group_name = app_type_{{ foo }}’ %}

I would do:

{% set group_name = ‘app_type’ + foo %}

And then in your loop, rather than doing ‘group_name’ you want the unquoted group_name:

{% for host in groups[ group_name ] %}

You should probably check what “group_name” got set to with your “set” statement and will probably find out it was not what you expected…

Works.

Not entirely sure how you ever actually write code due to your list contributions :slight_smile: Many thanks!