Level 1
0 / 100 XP

Ansible Playbook Error Handling

In this lesson, we will focus on managing errors within an Ansible playbook, particularly when an error is expected or planned as part of the playbook's logic. We'll use the scenario of the conditional_test.yml playbook, where the absence of a file is an expected outcome based on a conditional statement.

You will learn how to handle errors gracefully in Ansible playbooks, ensuring that your automation continues smoothly even when certain tasks fail.

Understanding Error Handling in Ansible

Error handling in Ansible is important when executing tasks that might fail under expected conditions. For example, in our conditional_test.yml playbook, the task to check for a file's existence might fail if the file was deliberately removed. Instead of letting this stop our playbook, we can configure our playbook to ignore / skip the error.

Modifying the Playbook for Error Handling

We will update the conditional_test.yml playbook to include a task that checks for the file's existence using the ls command. To handle potential errors, we'll use the ignore_errors directive, which tells Ansible to continue executing the playbook even if the task fails.

Open conditional_test.yml and add the following task at the end:

Text
- name: Check if the file exists command: ls ~/conditional_test_file.txt ignore_errors: True register: file_check

In this task, we're using the command module to run ls ~/conditional_test_file.txt. The ignore_errors: yes line ensures that even if the command fails (which it will if the file doesn't exist), the playbook will not stop executing. The output of the command is registered in the file_check variable.

Adding a Conditional Success Message

Next, let's add a task to display a success message if the file was correctly removed (i.e., if the previous task failed). We can use the file_check variable to determine if the command was successful or not.

Add th…