Ansible with_items vs loop

Question:

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

Answer:

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.

Leave a Reply