Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 439
manu Avatar asked Jan 16 '14 20:01

manu


People also ask

What is {{ item }} Ansible?

item is not a command, but a variable automatically created and populated by Ansible in tasks which use loops. In the following example: - debug: msg: "{{ item }}" with_items: - first - second. the task will be run twice: first time with the variable item set to first , the second time with second .

How do you use nested loops in Ansible?

Nested loops in many ways are similar in nature to a set of arrays that would be iterated over using the with_nested operator. Nested loops provide us with a succinct way of iterating over multiple lists within a single task. Now we can create nested loops using with_nested.

Which loop can be used to iterate over files in a directory Ansible?

Introduction to Ansible Loop. Ansible loop is used to repeat any task or a part of code multiple times in an Ansible-playbook. It includes the creation of multiple users using the user module, installing multiple packages using apt or yum module or changing permissions on several files or folders using the file module.

How are variables referenced in an Ansible template?

The variables are referenced through the Jinja2 template system, known to many from the Python language. It is very flexible. It supports both conditional expressions and loops. We reference the value of a variable in Jinja2 by placing its name inside double curly braces “{{ }}“.


1 Answers

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

like image 157
manu Avatar answered Oct 04 '22 00:10

manu