In this lab, you will explore the powerful error-handling features provided by Ansible's block
, rescue
, and always
directives. By deliberately introducing failures, you'll gain firsthand experience with how Ansible can gracefully handle errors and execute specific tasks based on the success or failure of previous tasks.
- Use the
block
directive to group related tasks. - Leverage the
rescue
directive to handle errors and provide recovery steps. - Utilize the
always
directive to ensure cleanup or follow-up tasks always execute.
- Ansible installed on your ansible machine.
- A target host or set of hosts configured in your Ansible inventory under the group
appservers
.
Estimated Time: 30 minutes
-
Create a new playbook named
error_handling_demo.yml
. -
Define the play structure:
--- - name: Error Handling Demo hosts: appservers become: yes become_user: root gather_facts: yes
-
Under the
tasks
section, define ablock
that encapsulates a series of tasks to execute sequentially:tasks: - name: Error handling demonstration block: - name: Print a success message debug: msg: "This task executes normally."
-
After the debug message, add a deliberate failure using the
command
module:- name: Introduce a failure command: /bin/false
-
Add a task that will not execute due to the failure:
- name: This task will be skipped debug: msg: "This will not execute due to the previous failure."
-
Add a
rescue
section to handle the error from theblock
:rescue: - name: Handle the error debug: msg: "An error occurred. Executing rescue tasks."
-
Optionally, add another deliberate failure in the
rescue
section:- name: Deliberate failure in rescue command: /bin/false
-
Add a task that will not execute due to the rescue failure:
- name: This will also be skipped debug: msg: "This will not execute due to the rescue failure."
-
Define an
always
section to include tasks that should execute regardless of success or failure:always: - name: Execute cleanup tasks debug: msg: "This task always executes."
-
Save the
error_handling_demo.yml
file. -
Run the playbook using:
ansible-playbook error_handling_demo.yml
-
Observe the output. The
block
section will fail, triggering therescue
section. When therescue
section also fails, its subsequent tasks will be skipped. Finally, thealways
section will execute.
You can compare your playbook with the error_handling_demo.yml file in the current directory.
The block
, rescue
, and always
directives provide a robust mechanism for error handling and cleanup in Ansible. These directives help you manage errors gracefully and ensure critical tasks always execute, even in the face of failures. Mastering these techniques will make your playbooks more resilient and reliable. 👏