Couuld you tell me What are the different between loop and with_items? and Which case we use loop which case we use with_items?
2 Likes
with_items is the old way of doing it, see the loops documentation.
2 Likes
short answer: loop is simple, with_X has magic, but in the end they do the same thing
long answer:
with_items is really loop + lookup('items'), so with_<any lookup can go here> is how loops worked, the items lookup has a implicit |flatten[1] filter so it is not exactly the same as loop: {{ lookup('items', mylist) }}, another lookup list is used for that aka with_list. A better example:
with_items:
- [1,2]
- [3,4]
will be a loop over 1,2,3,4:
[started TASK: debug on localhost]
ok: [localhost] => (item=1) => {
"msg": 1
}
ok: [localhost] => (item=2) => {
"msg": 2
}
ok: [localhost] => (item=3) => {
"msg": 3
}
ok: [localhost] => (item=4) => {
"msg": 4
}
while:
# or with_list
loop:
- [1,2]
- [3,4]
will loop over 2 items each of them a list::
[started TASK: debug on localhost]
ok: [localhost] => (item=[1, 2]) => {
"msg": [
1,
2
]
}
ok: [localhost] => (item=[3, 4]) => {
"msg": [
3,
4
]
}
This ‘magic’ lead to a lot of confusion with with_items and tthe other with_<<lookups>>, so loop was introduced to allow people to be able to use something simpler and less magical/hidden.
8 Likes