What you want is that file 1 and file 3 are always created, but file 2 is only created when test_var defined. If you use the possibility of use, provided that it works on the full task, and not on individual elements, for example:
- name: test task command: touch "{{ item.item }}" with_items: - { item: "1" } - { item: "2" } - { item: "3" } when: test_var is defined
This task will check the condition for all three positions 1,2 and 3.
However, you can achieve this with two simple tasks:
- name: test task command: touch "{{ item }}" with_items: - 1 - 3 - name: test task command: touch "{{ item }}" with_items: - 2 when: test_var is defined
source share