Skip a Loop based on a Condition#
Problem#
We want to skip an entire task that contains a loop. If we use when
as usual, the loop will still be evaluated, but each task will be skipped. So the following would not work:
skip_loop.yaml
- name: Cleanup Directory
hosts: web
vars:
expected_files:
- one.txt
- two.txt
- picture.jpg
grass: red
tasks:
- name: Clean up files
ansible.builtin.file:
path: "{{ item }}"
state: absent
loop: "{{ expected_files }}"
when: grass == "green"
Solution#
We use a condition in line of the template variable to execute the loop with an empty list.
skip_loop.yaml
- name: Cleanup Directory
hosts: web
vars:
expected_files:
- one.txt
- two.txt
- picture.jpg
grass: red
tasks:
- name: Clean up files
ansible.builtin.file:
path: "{{ item }}"
state: absent
loop: "{{ expected_files if grass == 'green' else [] }}"
Another common use case is to execute a run only if the variable containing the list is defined:
skip_loop.yaml
- name: Cleanup Directory
hosts: web
tasks:
- name: Clean up files
ansible.builtin.file:
path: ‘{{ item }}’
state: absent
loop: "{{ expected_files | default([]) }}"
Explanation#
If a task contains a loop, when
is evaluated for each element in this loop. Think of a loop as just a wrapper to execute the same task multiple times.