Ansible Handlers

Handlers are one of the core concepts of Ansible, and they are very useful. Ansible handlers are similar to the regular IT tasks within Ansible, and they are executed only when they are notified. It is essential in Ansible to run a task according to your needs which may be highly based on various factors. These include the condition of a service, the file’s existence, or following up tasks upon a state change. However, this blog will help you gain knowledge on Ansible Handler, its usage and importance in Ansible, and some key points on it. So, let us start with the introduction to an Ansible Handler.

What is an Ansible Handler?

An Ansible Handler is a specific task helpful to trigger some actions upon meeting specific conditions. These are used when there is a need for any change in an event while executing Ansible Playbooks. Ansible Handlers are generally used to execute tasks like resuming services, reloading configurations, or executing other tasks. They are only executed when they meet the required conditions.

Moreover, we can define Handlers in Ansible playbooks related to specific events. While executing a playbook, a task within it may need some changes which require handlers. Here, Ansible collects all handler actions and runs them once at the end of the play after executing all tasks.

Why do you use Handlers in Ansible?

Handlers in Ansible are highly useful for activating particular tasks concerning the changes made on the remote hosts. These handlers are primarily used to organize and manage specific changes in configurations. Also, they ensure that some tasks are executed when needed. These include tasks after configuration file changes or services are resumed.

Moreover, Ansible handlers are specifically helpful when you wish to execute specific tasks after meeting some conditions. You can run all those tasks with the help of handlers instead of executing them directly as individual tasks. Therefore, you can define those tasks as handlers and notify them to execute them upon meeting specific conditions.

Further, Ansible Handlers are very helpful to load, reload, resume, or halt services on target remote hosts. It is possible when there is a modification in the condition of an action.

Get ahead in your career by learning Ansible Course through hkrtrainings Ansible Online Training!

Ansible Training

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

How Do You Use Handlers In Ansible?

Handlers in Ansible are generally the tasks that are executed when activated through a directive “notify.” Once all the actions are completed, handlers will run when the play ends. To use Handlers, the following are the steps to consider:

  • Within the Ansible Playbook, you should define handlers by giving a name and mentioning the tasks required to be run by handlers.
  • Use the keyword “notify” to indicate which Ansible should get the notification that a specific task is completed.
  • Once the play comes to an end, handlers are executed when all the tasks in the play are executed.
  • Idempotence is a feature that handlers contain, which means executing them several times should have the same impact as executing them one time.

Step by Step guide on how to use Ansible Handlers

Here is a step-by-step process for using Ansible handlers in a specific task. First, you have to create the Playbook; then, you should run the Playbook to get the results.

1) Create the Playbook

Let us create a new Ansible Playbook displaying a hello world program. The following is the example syntax used for creating a playbook:

- name: My New Play
hosts: VM virtual machines
tasks:
- name: call my new hosts
ansible. builtin.call:
- name: Print the message
ansible. builtin. rectify:
msg: “Helllo-World.”
2) Execute the Playbook

Now, let us run the Playbook we created above. To start executing the Playbook, you need to open the terminal and by going to the directory of that Playbook, run the below example command:

ansible - playbook - i inventory. yaml playbook.yaml

Your Playbook is actively working now where the “inventory. yaml” file is known as inventory, and the “playbook.yml” is a playbook. Now you can use Ansible Handlers to execute tasks discussed in the following parts.

We have the perfect professional Ansible Tutorial for you. Enroll now!

Subscribe to our YouTube channel to get new updates..!

Ansible Handlers Key Points

  • Ansible handlers are only executed when specific conditions are met upon completion of tasks in a play.
  • To trigger or activate the handler, the keyword “notify” is used within the tasks.
  • Handlers can use the similar syntax used by the tasks and the Ansible modules they use.
  • Generally, all Ansible handlers are kept inside a directory of handlers within a playbook.
  • After creating a playbook, you can run the handler once within a play, even if they are notified several times.
  • Here, the handlers should relate to the name of the tasks. The attribute “name” should match the trigger “Notify” within the task.
  • All handlers should be idempotent, indicating that all the handlers executed safely without the impact of unknown issues or changes.
A Single task and a handler

In continuation to the creation of Playbook, in the earlier discussion, you will find how to use the Ansible handler for a single task after creating a Playbook. The task is to install Apache along with handlers.

---
- name: Configure Web Servers
hosts: web servers
become: true
tasks:
  - name: Install Apache
  apt:
   name: apache2
   state: present
   notify: Resume Apache
handlers:
  - name: Resume Apache
    service:
    name: apache2
    state: resumed

Here, the Ansible playbook includes a routine task along with a handler. The task installs the Apache Server on the target remote device. After installation, the trigger “notify” calls the task handler, which restarts Apache Services.

IMAGE

Multiple tasks and handlers

Sometimes you may need to deal with different tasks which require the use of multiple handlers. Here, you will see there are two tasks to execute:

  • Apache web server installation
  • Enabling the HTTP traffic on the firewall system - UFW

In this, one handler will help resume the Apache server, and another will reload the Ufw firewall system. Once all the tasks are executed without any issues, you can call the handlers along with the “notify” trigger as follows:

 ---
 - hosts: staging
 name: Install
 become: true
 tasks:
      - name: Install Apache2 on a new server- Ubuntu
      apt:
          name: apache2
          state: present
          update_cache: true
 - name: Enable the HTTP traffic on the firewall system - UFW
 ufw:
    rule: enable
    port: http
    proto: TCP
 notify:
   - Resume apache2
   - Reload the firewall ufw
 handlers:
  - name: Resume Apache2
 service:
     name: apache2
     state: resumed
 - name: Reload firewall system - UFW
ufw:
     state: enabled

Click here to get latest Ansible Interview Questions and Answers for 2022!

Ansible Training

Weekday / Weekend Batches

Conclusion

Thus, you have briefly reviewed the basics of Ansible Handlers and their importance. Also, you have learned how to use the Ansible Handlers in multiple ways as regular tasks, along with creating and running a playbook. We hope you got an overall idea of installing the Apache server using various handlers in Ansible. 

Related Articles:

Find our upcoming Ansible Training Online Classes

  • Batch starts on 29th Sep 2023, Fast Track batch

  • Batch starts on 3rd Oct 2023, Weekday batch

  • Batch starts on 7th Oct 2023, Weekend batch

Global Promotional Image
 

Categories

Request for more information

Amani
Amani
Research Analyst
As a content writer at HKR trainings, I deliver content on various technologies. I hold my graduation degree in Information technology. I am passionate about helping people understand technology-related content through my easily digestible content. My writings include Data Science, Machine Learning, Artificial Intelligence, Python, Salesforce, Servicenow and etc.

Ansible playbooks consist of various tasks that automatically run for a specific inventory or collection of hosts. A play includes single or multiple tasks, and a sequence of tasks is mapped to particular hosts. Then these Ansible tasks are executed in order.

Handlers in Ansible are specific tasks only executed when certain conditions are met. Further, Handlers help start, resume, reload, and halt the services on the target device.

To handle the contrast between multiple systems, Ansible uses variables that can be created using the basic YAML syntax, lists, dictionaries, etc.