Skip the whole loop in Ansible

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

In accordance with the recommendations

When combining when with with_items (see "Loops"), the ... when operator is processed separately for each element.

Thus, during the work of such a play

 --- - 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) 

While I do not want the 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 [] }}" 

I seem to have solved my problem, but then I get nothing. And I want only one line:

 skipping: Loop has been skipped 
+5
source share
2 answers

You should be able to get Ansible to evaluate a condition only once with Ansible 2 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 be displayed for each element and each node, but as udondan noted, if you want to suppress the output, you can add:

 display_skipped_hosts=True 

to the ansible.cfg file .

+2
source

This can be done easily by using include along with the condition:

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

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

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

All Articles