manu
manu

Reputation: 1017

How to loop over array containing template variables with ansible?

I'm setting up an automated provisioning process for a webserver using Ansible. For this, I have an array containing dictionaries with vhosts to setup:

vhosts:
  -
    name: 'vhost1'
    server_name: 'domain1.com'
  -
    name: 'vhost2'
    server_name: 'domain2.com'

I prepared a template with some generic nginx vhost configuration:

server {
    listen 80;
    server_name {{ item.server_name }};

    root    /home/www/{{ item.name }}/htdocs;
    index   index.php;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }
}

Finally, I use the following task to copy a prepared template to the target host:

- name: Setup vhosts
  template: src=vhost.j2 dest=/etc/nginx/sites-available/{{ item.name }}
  with_items: vhosts

The tasks iterates over the vhost variable as expected. Unfortunately, Ansible does not pass the current item from the iterator to the template, instead the template has access to all currently valid variables.

Is there any way to pass the current item from the iterator to the template?

Upvotes: 11

Views: 7330

Answers (1)

manu
manu

Reputation: 1017

turns out that the code above works absolutly perfect. there was another problem in my variables YAML file.

Upvotes: 8

Related Questions