Ansible - End play using the fail module
by
Jeremy Canfield |
Updated: June 21 2023
| Ansible articles
If you are not familiar with modules, check out Ansible - Getting Started with Modules.
There are a number of ways to do something when a task returns an error.
- Use fail to end a play and return "failed" (this article)
- Use the --check command line flag to run the playbook in a dry run mode
- Use check_mode to determine if any fatal errors would be returned
- Use failed_when to continue based on the task return code
- Use ignore_errors to ignore errors returned by a task
- Use meta: clear_host_errors to clear errors so that subsequent tasks are run
- Use meta: end_play to end a play for all hosts
- Use meta: end_host to end a play for certain hosts and return "skipped"
- Use block rescue always to run tasks even after a fatal error is returned
- Use stat to determine if /tmp/foo.txt exists and the when parameter to skip the lineinfile module if /tmp/foo.txt does not exist.
- Use stat to determine if /tmp/foo.txt exists and then use the file module and the when parameter to create /tmp/foo.txt if the file does not exist
The fail module is used to end a play for a host when a certain condition is met. In this example, the playbook will fail when the foo variable is undefined.
---
- hosts: localhost
tasks:
- name: fail when the 'foo' variable is undefined
fail:
msg: the 'foo' variable is undefined
when: foo is undefined
...
It's important to recognize that when the when condition in the fail module evaluates to true:
- The play will be ended for the host meaning that the subsequent tasks in the playbook will not be executed on the host
- The task to return fatal and the PLAY RECAP with have failed=1.
meta: end_host can be used if you want the PLAY RECAP to have "skipped" instead of "failed".
TASK [fail when the 'foo' variable is undefined]
fatal: [server1.example.com]: FAILED! => {"changed": false, "msg": "The 'foo' variable is undefined"}
PLAY RECAP *********************************************************************
server1.example.com : ok=0 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
Did you find this article helpful?
If so, consider buying me a coffee over at