loopsansible

Skip a task that contains a loop


Ansible documentation states that a when condition is executed for every item in a loop.

But, is there a "task global" condition (i.e. when the when clause is false, the whole task is skipped)?


Solution

  • There is no "task global" condition, indeed, but you can easily skip a task that contains a loop if the list you are looping on is empty.

    So, if you bake your condition right into your templated loop variable, for example, with an inline if, then you can achieve your desired behaviour.

    For exemple:

    - name: Skip the whole task
      ansible.builtin.debug:
        var: item
      loop: "{{ range(1,5) if not should_skip else [] }}"
      vars:
        should_skip: true
    

    Which produce the output:

    TASK [Skip the whole task] ****************************************
    skipping: [localhost]
    

    Also mind that filters like select, reject, selectattr and rejectattr could help you filter down your list to a possibly empty one based on conditions.


    This is, based on needs, arguably cleaner than

    - name: Skip the whole task
      ansible.builtin.debug:
        var: item
      loop: "{{ range(1,5) }}"
      when: not should_skip
      vars:
        should_skip: true
    

    Producing

    TASK [Skip the whole task] ****************************************
    skipping: [localhost] => (item=1) 
    skipping: [localhost] => (item=2) 
    skipping: [localhost] => (item=3) 
    skipping: [localhost] => (item=4) 
    skipping: [localhost]