when and with on same variable

  • debug: msg=“test for items” # skip because condition is not fullfiled
    when: groups.unexisting is defined

  • debug: msg=“test for items”
    when: groups.unexisting is defined

with_items: unexisting #failed here with with_items expects a list or a set

  • debug: msg=“test for items”
    when: groups.unexisting is defined

with_items: groups.unexisting #might work if you reference the same variable?

when gets evaluated INSIDE the with loop, so it cannot condition the
executing of with, this is done so you can do when: item == 'blah' for
example to condition each iteration in the loop.

to deal with undeinfed with_ vars, do the following:

with_ : "{{ myvar|default()}}"

^ the empty will skip the task as there is nothing to loop over.

some times you need more complex conditions, ternary filter can help:

with_ : "{{ unexisting is defined|ternary( groups['unexisting'], ) }}"