Ansible - until parameter (while loop)

by
Jeremy Canfield |
Updated: July 20 2023
| Ansible articles
The retries and delay and until parameters can be used to mimic a while loop.
In this example, the ps command will be executed once every 10 seconds (delay: 10) until string "Hello World" is found in the stdout (until), a maximum of 5 times (retries: 5).
---
- name: localhost play
hosts: localhost
tasks:
- shell: ps -ef | grep 'Hello World'
register: result
retries: 5
delay: 10
until: result.stdout is search 'Hello World'
...
If each retry fails, something like this should be returned.
TASK [shell]
FAILED - RETRYING: command (5 retries left).
FAILED - RETRYING: command (4 retries left).
FAILED - RETRYING: command (3 retries left).
FAILED - RETRYING: command (2 retries left).
FAILED - RETRYING: command (1 retries left).
fatal: [localhost]: FAILED! => {"attempts": 5, "changed": true, "cmd": "ps -ef | grep 'Hello World'", "delta": "0:00:00.017862", "end": "2023-07-20 05:08:31.791651", "rc": 0, "start": "2023-07-20 05:08:31.773789", "stderr": "", "stderr_lines": [], "stdout": "john.doe 10911 10906 0 05:08 pts/0 00:00:00 /bin/sh -c ps -ef | grep foo\njohn.doe 10913 10911 0 05:08 pts/0 00:00:00 grep foo", "stdout_lines": ["john.doe 10911 10906 0 05:08 pts/0 00:00:00 /bin/sh -c ps -ef | grep foo", "john.doe 10913 10911 0 05:08 pts/0 00:00:00 grep 'Hello World'"]}
On the other hand, if at least one of the tries was successful, the TASK result should be OK or changed and then the playbook should move onto the next task in the playbook.
TASK [shell]
changed: [localhost]
Did you find this article helpful?
If so, consider buying me a coffee over at