Table of contents
1.
Introduction
2.
Understanding Ansible Handlers
3.
Ninjas Toolkit for Ansible Handlers
4.
Facts in Ansible Handlers
5.
Syntax of Ansible Handlers
6.
Examples of Ansible Handlers
6.1.
Grouping Handlers with the ‘Listen’ Directive
7.
Uses of Ansible Handlers
8.
Frequently Asked Questions
8.1.
What is Ansible automation software?
8.2.
When are ansible handlers executed?
8.3.
How to define an Ansible handler?
8.4.
Can there be more than one handler in a playbook?
9.
Conclusion 
Last Updated: Mar 27, 2024
Medium

Ansible Handlers

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Ansible is a free-to-use command line automation software written in Python that provides many tools to automate IT. It is used to set up systems, deploy software, perform updates, and many more. Ansible Handlers are a key feature of the Ansible automation software that triggers specific actions or tasks when certain conditions are met.

Ansible Handlers

In this article, we will be discussing Ansible Handlers in detail with some examples.

Understanding Ansible Handlers

Ansible handlers are tasks that are executed when triggered by the notify directive after a certain set of conditions are fulfilled. Handlers are run at the end of the play. Thus their actions occur when all the tasks are completed. This prevents any repeated actions in the files. They manage the start, stop, reload, and restart services. 

Handlers can be used in situations where the changes to the config files ask for a restart service to update the files. 

Ninjas Toolkit for Ansible Handlers

Here are some tips that can be followed while working with Ansible handlers.

  • The name of each handler should be distinct such that it can be used to call it through a notifier.
     
  • When two handlers have the same name, only the latter gets executed.
     
  • The use of variables in the handler's name should be avoided.
     
  • Handlers always run in the same order they are defined in the playbook.
     
  • The 'listen' feature can be used to call multiple handlers with a single 'notify.'
     
  • The notification does not activate the handler if the state of the task does not change,  

Facts in Ansible Handlers

Ansible has some predefined variables called facts that are used to collect information about remote nodes. These facts are stored in JSON format and provide real-time data. The facts might either be the IP address, MAC address, OS details, hostname, system status, etc. 

Ansible Handlers use the facts to make decisions based on the attributes of each node. We can also add conditions with the help of facts within the handlers.

Syntax of Ansible Handlers

The Ansible handlers are defined in a playbook with the help of the 'name' key. The syntax of Ansible handlers is shown below.

hosts: all
tasks:
 - name: Task 1
      # Task 1 configuration here
 - name: Task 2
      # Task 2 configuration here
    <Module Definition>
    notify: <Name of the Handler>
handlers:
  - name: <Name of the Handler>
    <Module Definition>

Examples of Ansible Handlers

First, create a new file called ansible_handlers.yml in the ansible-practice folder:

nano ~/ansible-practiceansible_handlers.yml

 

In the example given below, we will install the apache2 package on remote nodes. After the package is installed successfully, the state of the handler gets changed. A notifier is also mentioned here, which will call the handler to restart the apache2 service after the change in the task state.

Code

hosts: all
  tasks:
    - name: Install apache2
      yum:
        name: apache2
        state: installed
      notify:
        - Start Apache
handlers:
    - name: Start Apache
      service:
        name: apache2
        state: started

 

Next, Run the ansible playbook ansible_handlers to have a look at the tasks and handlers defined.

ansible-playbook ansible_handlers.yaml

 

If we rerun the playbook and the tasks do not change, the notifier does not call the handler this time. This is because the handler is activated by the tasks that result in changes, and since the packages are already installed, there is no need to rerun the handler again.

Grouping Handlers with the ‘Listen’ Directive

We can also use the 'listen' feature to call multiple handlers with the help of a single notify. 

Code

- name: Setup Web Servers
  hosts: all
  tasks:
    - name: Install Apache Web Server
      yum:
        name: httpd
        state: installed
      notify: Start Web Service
  handlers:
    - name: Start Web Service
      service:
        name: httpd
        state: started
      listen: Web Server Configuration
    - name: Copy index.html from Control Server
      copy:
        src: /var/tmp/index.html
        dest: /var/www/html/index.html
      listen: Web Server Configuration

 

In the above code, notifying the listener topic "web server configuration" calls two handlers, one to start the Apache HTTP server service and the other to copy the index.html from local to remote nodes.

Now we can use the Ansible facts such as 'ansible_hostnames' to run a task based on certain conditions. This helps us decide which web server package (httpd or Nginx) will be installed.

Code

- name: Configure Web Servers
  hosts: all
  tasks:
    - name: Install HTTPD on host-one and Nginx on host-two
      command: echo "Web Server Installation Begins"
      notify: "Install Web Server"
  handlers:
    - name: Install HTTPD
      yum:
        name: httpd
        state: installed
      when: ansible_hostname == "host-one"
      listen: "Install Web Server"
    - name: Install Nginx
      yum:
        name: nginx
        state: installed
      when: ansible_hostname == "host-two"
      listen: "Install Web Server"


With the above code, we can conditionally install a web server package on each server based on the host names.

Uses of Ansible Handlers

The uses of ansible handlers are:

  • Ansible Handlers are used in managing the start, stop, reload, and restart services on remote nodes.
     
  • Ansible handlers are used to handle errors and correct them.
     
  • They respond to tasks like package installation, thus making them a good choice for event-based actions.
     
  • It can also be used to send alerts based on certain conditions.
     
  • They are used in maintenance tasks like data backups and data recovery.

Frequently Asked Questions

What is Ansible automation software?

Ansible is an open-source command line automation software that is written in Python. It provides many tools to automate IT. It is used to set up systems, perform updates, deploy software, and many more tasks.

When are ansible handlers executed?

Ansible Handlers are executed at the end of the play after all the tasks in the play are completed. They are triggered when there are any changes in the playbook by the tasks. If there are no changes, the handlers are not executed. 

How to define an Ansible handler?

Ansible Handlers are defined in the handler section of the Ansible playbook. Here the name of the ansible handler and the respective tasks to be run by the handler are specified. 

Can there be more than one handler in a playbook?

Yes, there can be more than one Ansible handler in the handlers section of an Ansible playbook. However, it should be noted that each handler has its own name and tasks.

Conclusion 

Ansible Handlers are a key feature that allows engineers to perform targeted actions based on certain events or changes. It is the fundamental tool that greatly increases the efficiency and reliability of automation workflows.

We hope this blog has helped you understand the Ansible Handlers better. Keep learning! We suggest you read some of our other articles related to Ansible: 

  1. Introduction to Ansible
  2. Ansible playbooks
  3. Ansible interview Questions
     

Refer to our Guided Path to enhance your skills in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas!

But suppose you are just a beginner and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. For placement preparations, you must look at the problemsinterview experiences, and interview bundles.

Best of Luck! 

Happy Learning!

Live masterclass