What is the difference between using with_items vs loops in ansilbe?
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.
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.
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.
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 .
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.
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
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