What should I do if I want to skip the whole loop in Ansible?
According to guidelines,
While combining
when
withwith_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
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.
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