Nick Roz
Nick Roz

Reputation: 4230

Skip the whole loop in Ansible

What should I do if I want to skip the whole loop in Ansible?

According to guidelines,

While combining when with with_items (see Loops), ... when statement is processed separately for each item.

Thereby while running the playbook like that

---
- hosts: all
  vars:
    skip_the_loop: true
  tasks:
    - command: echo "{{ item }}"
      with_items: [1, 2, 3]
      when: not skip_the_loop

I get

skipping: [localhost] => (item=1) 
skipping: [localhost] => (item=2) 
skipping: [localhost] => (item=3)

Whereas I don't want a condition to be checked every time.

Then I came up with the idea of using inline conditions

- hosts: all
  vars:
    skip_the_loop: true
  tasks:
    - command: echo "{{ item }}"
      with_items: "{{ [1, 2, 3] if not skip_the_loop else [] }}"

It seems to solve my problem, but then I get nothing as output. And I want only one line saying:

skipping: Loop has been skipped

Upvotes: 6

Views: 4313

Answers (3)

Ben
Ben

Reputation: 60

If there's a lot of items, you might find this solution runs faster. It loops over the empty list when skip_the_loop is true.

---
- hosts: all
  vars:
    skip_the_loop: true
  tasks:
    - command: echo "{{ item }}"
      loop: "{{ skip_the_loop | ternary([], [1, 2, 3]) }}"

Upvotes: 1

Nick Roz
Nick Roz

Reputation: 4230

This can be done easily using include along with condition:

hosts: all
  vars:
    skip_the_loop: true
  tasks:
    - include: loop
      when: not skip_the_loop

Whereas somewhere in tasks/ there is a file called loop.yml:

- command: echo "{{ item }}"
  with_items: [1, 2, 3]

Upvotes: 0

ydaetskcoR
ydaetskcoR

Reputation: 56859

You should be able to make Ansible evaluate the condition just once with Ansible 2's blocks.

---
- hosts: all
  vars:
    skip_the_loop: true
  tasks:
    - block:
      - command: echo "{{ item }}"
        with_items: [1, 2, 3]
      when: not skip_the_loop

This will still show skipped for every item and every host but, as udondan pointed out, if you want to suppress the output you can add:

display_skipped_hosts=True

to your ansible.cfg file.

Upvotes: 3

Related Questions