Ansible - Retry a task using the retries parameter

by
Jeremy Canfield |
Updated: August 24 2022
| Ansible articles
The retries parameter can be used to retry a task. In this example, you want to retry the ps command 3 times. The retries option is often used with the delay option.
---
- hosts: localhost
tasks:
- name: ps command
shell: "ps -ef | grep httpd"
retries: 3
delay: 3
register: out
until: out.rc == 0
...
In this example, the return code of the ps command will be 0 (success) when there is an HTTPD process running on the managed node (e.g. target system). On the other hand, the return code will be 1 (failed) when there are no HTTPD processes running on the managed node. In this example, as long as the return code is not 0, the ps command will be retried 3 times.
Running this play should produce the following.
PLAY [all]
TASK [ps command]
FAILED - RETRYING: ps command (3 retries left).
FAILED - RETRYING: ps command (2 retries left).
FAILED - RETRYING: ps command (1 retries left).
fatal: [localhost]: FAILED! => {"attempts": 3, "changed": true, "cmd": "ps -ef | grep httpd", "delta": "0:00:00.014413", "end": "2020-07-20 05:23:37.348236", "msg": "non-zero return code", "rc": 1, "start": "2020-07-20 05:23:37.333823", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
PLAY RECAP
localhost : ok=1 changed=0 unreachable=0 failed=1
Did you find this article helpful?
If so, consider buying me a coffee over at