How to break from the loop in Ansible
Generally, it thought to be impossible. But if you really want to, you can.
The problem
To stop Ansible loop if one of the calls to the module returned changed. Basically, to write in Ansnible this:
for x in list_of_items:
res = module(x)
if res.changed:
break
The problem is that there is no ‘break’ keyword or any other analogue in Ansible.
The solution
---
- hosts: localhost
tasks:
- file:
path: '{{ item }}'
state: directory
register: res
when: not (res.changed|d(false))
loop: '{{ list_of_items }}'
vars:
list_of_items:
- /etc
- /bin
- example1
- example2
- example3
The trick here is that res.changed
for registered task is changing on each iteration. There is res.results, but we are not care about it much.
If you run this script, it would make ‘no change’ for /etc and /bin, and will create example1
directory, and skip other examples
On a second run it would create example2
, and skip the rest.