Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible with_items vs loop

Tags:

What is the difference between using with_items vs loops in ansilbe?

like image 403
Mohd Abdul Mujib Avatar asked May 21 '18 21:05

Mohd Abdul Mujib


People also ask

What is difference between loop and With_items in Ansible?

Ansible documentation recommend user to use or replace with_items with loop. So, with_items is the older way of writing Ansible playbooks and loop is the newer way of writing the playbook. For most part they are almost identical.

Can we loop over two parallel sets in Ansible?

You can nest two looping tasks using include_tasks . 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.

What are loops in Ansible?

Ansible loops are very effective to perform repetitive tasks with fewer lines of code. Ansible provides the loop , with_<lookup> , and until keywords to execute a task multiple times.

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 .


2 Answers

Update: The most recent Documentation lists down the differences as below

  • The with_ keywords rely on Lookup Plugins - even items is a lookup.
  • The loop keyword is equivalent to with_list, and is the best choice for simple loops.
  • The loop keyword will not accept a string as input, see Ensuring list input for loop: query vs. lookup.
  • Generally speaking, any use of with_* covered in Migrating from with_X to loop can be updated to use loop.
  • Be careful when changing with_items to loop, as with_items performed implicit single-level flattening. You may need to use flatten(1) with loop to match the exact outcome.

Old answer

As per the docs,

Before 2.5 Ansible mainly used the with_ keywords to create loops, the loop keyword is basically analogous to with_list.

So basically they are pretty much the same, only the newer version uses loop in its syntax. And as of version 2.7.12 both work as expected but using the loop keyword is encouraged for future compatibility.

like image 174
Mohd Abdul Mujib Avatar answered Sep 28 '22 11:09

Mohd Abdul Mujib


They are different. Be careful when changing with_items to loop, as with_items performed implicit single-level flattening. You may need to use flatten with loop to match the exact outcome. look at the official doc examples.

Ansible Loops

like image 29
peyman Avatar answered Sep 28 '22 09:09

peyman