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?
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 .
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.
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.
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 “{{ }}“.
turns out that the code above works absolutly perfect. there was another problem in my variables YAML file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With