Skip to main content

Error Handling in Ansible

When working with Ansible, it's common to encounter some errors. As a playbook grows in complexity, it's essential to understand how to handle these effectively. In this tutorial, we'll explore error handling in Ansible.

Error Handling Methods

Fail Module

The fail module in Ansible makes a task fail immediately. It's commonly used to make a task fail when a certain condition is met.

- name: Fail task
fail:
msg: "The task has failed."
when: condition

In this example, if the condition is met, the task fails immediately and returns the message "The task has failed."

Ignore Errors

In some cases, you might want a task to continue even if it fails. You can achieve this using the ignore_errors directive.

- name: Ignore errors
command: /bin/false
ignore_errors: true

In this snippet, the task will continue running even if the command /bin/false fails.

Changed When

The changed_when statement is used to override the default condition under which Ansible considers a task as changed.

- name: Change conditions
command: /bin/something
register: result
changed_when: "'FAILED' in result.stdout"

In this case, the task is considered changed only when 'FAILED' is in the stdout of the task.

Using Blocks for Error Handling

In Ansible, a block contains a group of tasks that are logically grouped. Error handling can be applied to all tasks within a block using rescue and always clauses.

- name: Block with error handling
block:
- debug:
msg: 'This is the start of the block'
- command: /bin/false
- debug:
msg: 'This command will not be printed'
rescue:
- debug:
msg: 'This is the rescue section'
always:
- debug:
msg: 'This is always executed'

In this block, if the command /bin/false fails, the playbook jumps to the rescue section. The always section runs regardless of the outcome.

Registering Variables

Using the register keyword, the output of a task can be saved and used in subsequent tasks. This is helpful for error handling.

- name: Register variable
command: /bin/something
register: result
failed_when: "'FAILED' in result.stdout"

In this case, we're registering the output of the command to a variable 'result'. The task will fail when 'FAILED' is in the stdout.

Max Fail Percentage

The max_fail_percentage directive allows you to specify a percentage of hosts in which if more than the specified percentage fails, the play is halted.

- hosts: webservers
max_fail_percentage: 30
tasks:
- name: This is a test task
command: /bin/something

In this example, if more than 30% of hosts fail, the play is halted.

Conclusion

Error handling in Ansible is a crucial aspect of playbook development. Through methods such as the fail module, ignore_errors, changed_when, blocks, register, and max_fail_percentage, you can effectively manage and control the errors in your Ansible playbook.