Nested loop in template

Hi,

I’m trying to create an Apache vhost config file using a legacy yaml file that I can’t change.

I’m nearly there, but the nested loop in the template doesn’t work as expected.

Here’s the yaml:

sites:

site1.com:

vhosts:

other1: blah

other2: blah

etc

etc

site50.com:

vhosts:

other1: blah

other2: blah

Here’s my play:

  • name: Populate vhost config

template: src=httpd.j2 dest=/etc/httpd/conf.d/vhosts.conf

with_dict: “{{ sites }}”

Here’s my template:

<VirtualHost *>

{% for site in sites %}

ServerName {{ site }}

{% for vhost in item.value.vhosts %}

ServerAlias {{ vhost }}

{% endfor %}

DocumentRoot /var/www/html/{{ site }}

<Directory /var/www/html/{{ site }}

AllowOverride All

Order allow,deny

Allow from All

{% endfor %}

Expected result:

<VirtualHost *>

ServerName site1.com

ServerAlias vhost1.com

ServerAlias vhost2.com

ServerAlias vhost3.com

DocumentRoot /var/www/html/site1.com

<Directory /var/www/html/site1.com

AllowOverride All

Order allow,deny

Allow from All

etc

etc

ServerName site50.com

ServerAlias vhost51.com

ServerAlias vhost52.com

ServerAlias vhost53.com

DocumentRoot /var/www/html/site50.com

<Directory /var/www/html/site50.com

AllowOverride All

Order allow,deny

Allow from All

etc.

etc.

Actual result:

<VirtualHost *>

ServerName site1.com

ServerAlias vhost51.com

ServerAlias vhost52.com

ServerAlias vhost53.com

DocumentRoot /var/www/html/site1.com

<Directory /var/www/html/site1.com

AllowOverride All

Order allow,deny

Allow from All

etc

etc

ServerName site50.com

ServerAlias vhost51.com

ServerAlias vhost52.com

ServerAlias vhost53.com

DocumentRoot /var/www/html/site50.com

<Directory /var/www/html/site50.com

AllowOverride All

Order allow,deny

Allow from All

etc.

etc.

Solved it - had to use “key,value” - here is the revised template:

<VirtualHost *>
{% for site,value in sites.iteritems() %}
ServerName {{ site }}
{% for vhost in value.vhosts %}
ServerAlias {{ vhost }}
{% endfor %}
DocumentRoot /var/www/html/{{ site }}
<Directory /var/www/html/{{ site }}
AllowOverride All
Order allow,deny
Allow from All

{% endfor %}

iteritems() is there to get around the “too many values to unpack” problem.