I have this structure:
addresses:
- 192.168.1.1
- 192.168.2.2
- 192.168.3.3
I need to process them in the task:
- tasks:
- name: Iterating
- template: src=template.j2 dest=/etc/addresses/{{index}}.conf
with_items: addresses
But I can't find any way to fill index variable (or any other similar trick).
Note: I know about indexes inside j2 templates, but I'm talking about tasks.
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 .
In this article, we are going to learn about Ansible List. and How to create Ansible List and append items to it. The LIST is a type in data structure and is widely used in all programming languages. It is to store a group of heterogeneous elements.
Defining inner and outer variable names with loop_var However, by default Ansible sets the loop variable item for each loop. This means the inner, nested loop will overwrite the value of item from the outer loop. You can specify the name of the variable for each loop using loop_var with loop_control .
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.
You can use with_indexed_items
, another Ansible standard loop.
- tasks:
- name: Iterating
template: src=template.j2 dest=/etc/addresses/{{ item.0 }}.conf
with_indexed_items: addresses
The address item can be accessed in the template as {{ item.1 }}
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