Is it possible to skip some items in Ansible with_items
loop operator, on a conditional, without generating an additional step?
Just for example:
- 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.
item is not a command, but a variable automatically created and populated by Ansible in tasks which use loops. In the following example: - debug: msg: "{{ item }}" with_items: - first - second. the task will be run twice: first time with the variable item set to first , the second time with second .
Ansible documentation recommend user to use or replace with_items with loop. So, with_items is the older way of writing Ansible playbooks and loop is the newer way of writing the playbook. For most part they are almost identical.
Nested loops in many ways are similar in nature to a set of arrays that would be iterated over using the with_nested operator. Nested loops provide us with a succinct way of iterating over multiple lists within a single task. Now we can create nested loops using with_nested.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With