Skip specific items provided that in_items loop

Is it possible to skip some elements in the Ansible with_items loop with_items , conditional, without creating an extra step?

For example only:

 - name: test task command: touch "{{ item.item }}" with_items: - { item: "1" } - { item: "2", when: "test_var is defined" } - { item: "3" } 

in this task, I want to create file 2 only when test_var defined.

+10
source share
4 answers

Another answer is close, but will skip all the elements! = 2. I do not think you want. here is what i will 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 
+16
source

The when: condition for a task is evaluated for each element. Therefore, in this case, you can simply:

 ... with_items: - 1 - 2 - 3 when: item != 2 and test_var is defined 
+4
source

I had a similar problem and I did the following:

 ... with_items: - 1 - 2 - 3 when: (item != 2) or (item == 2 and test_var is defined) 

Which is simpler and cleaner.

+2
source

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 
0
source

All Articles