Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enumerate list in ansible?

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.

like image 586
George Shuklin Avatar asked Jan 13 '16 14:01

George Shuklin


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 .

What is a list in Ansible?

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.

What is Loop_var in Ansible?

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 .

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.


1 Answers

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 }}

like image 162
udondan Avatar answered Sep 23 '22 20:09

udondan