Skip certain items on condition in ansible with_items loop
The when:
conditional on the task is evaluated for each item. So in this case, you can just do:
...
with_items:
- 1
- 2
- 3
when: item != 2 and test_var is defined
The other answer is close but will skip all items != 2. I don't think that's what you want. here's what I would do:
- hosts: localhost
tasks:
- debug: msg="touch {{item.id}}"
with_items:
- { id: 1 }
- { id: 2 , create: "{{ test_var is defined }}" }
- { id: 3 }
when: item.create | default(True) | bool