Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 568
Nick Roz Avatar asked Oct 18 '22 07:10

Nick Roz


1 Answers

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.

like image 82
ydaetskcoR Avatar answered Nov 04 '22 00:11

ydaetskcoR