Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Ansible Role Handlers

1. What are Handlers?

Handlers are special tasks in Ansible that only run when notified. They are used to handle changes that may require additional actions, such as restarting a service after a configuration file has been modified.

Handlers are defined in the same way as regular tasks but are triggered by the notify directive in other tasks.

2. Creating Handlers

Handlers are defined in the handlers section of a role or playbook. Here’s an example of how to create a handler:


- name: Restart Apache
  service:
    name: httpd
    state: restarted
                

3. Using Handlers

To use a handler, you must notify it in a task. Here’s an example:


- name: Install Apache
  yum:
    name: httpd
    state: present
  notify: Restart Apache
                

4. Best Practices

  • Keep handlers simple and focused on a single task.
  • Always document what each handler does for easier maintenance.
  • Use descriptive names for handlers to improve readability.
  • Group related handlers together for better organization.

5. FAQ

What happens if a handler is notified multiple times?

If a handler is notified multiple times during a play, it will only run once at the end of the play.

Can handlers be defined in a role?

Yes, handlers can be defined within a role's handlers/main.yml file.

How do I prevent a handler from running multiple times?

Handlers are designed to run once per play, no matter how many times they are notified.

6. Flowchart of Handler Usage


graph TD
    A[Start] --> B[Create Task]
    B --> C{Task Changed?}
    C -- Yes --> D[Notify Handler]
    C -- No --> E[End]
    D --> F[Execute Handler]
    F --> E