Question:
Is it possible to skip some items in Ansible with_items
loop operator, on a conditional, without generating an additional step?
Just for example:
1 2 3 4 5 6 7 |
- 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
is defined.
Answer:
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:
1 2 3 4 5 6 7 8 9 |
- 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 |