Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Ansible Playbook Handlers

1. Introduction

Handlers in Ansible are special tasks that run at the end of the playbook execution when notified by other tasks. They are typically used for operations that should only occur when a change has been made, such as restarting a service after a configuration file has been updated.

2. What are Handlers?

Handlers are defined similarly to regular tasks, but they respond to notifications. When a task changes something, it can notify a corresponding handler to perform an action. Handlers ensure that these actions are executed only when necessary, helping to optimize playbook execution time.

Note: Handlers are executed at the end of the play, after all tasks have been run.

3. Defining Handlers

Handlers are defined within the playbook under the `handlers` section. Here’s a simple example:


- hosts: webservers
  tasks:
    - name: Update the web server configuration
      copy:
        src: /path/to/config
        dest: /etc/webserver/config
      notify: Restart webserver

  handlers:
    - name: Restart webserver
      service:
        name: webserver
        state: restarted
        enabled: yes
        

4. When to Use Handlers

Handlers should be used in scenarios where:

  • Changes to a configuration file require a service restart.
  • Changes to a package installation require a service reload.
  • Any task that should only run if a previous task indicated a change has occurred.

5. Best Practices

When using handlers, consider the following best practices:

  1. Keep handlers simple: Use them for tasks that are quick and do not rely on complex logic.
  2. Group related tasks: Define handlers that are logically grouped together to avoid redundancy.
  3. Use descriptive names: Name handlers clearly to indicate their purpose (e.g., `Restart apache`, `Reload nginx`).
  4. Limit notifications: Only notify handlers from tasks that require a change to reduce unnecessary executions.

6. FAQ

Can a handler run multiple times in one play?

No, a handler will only run once per play, even if notified multiple times.

What happens if a handler fails?

If a handler fails, the playbook will proceed to the next task, but the failure will be reported.

Are handlers specific to a play?

Yes, handlers are defined within a specific play and are not accessible outside that play.