Ubuntu

How To Define and Use Handlers in Ansible Playbooks

How To Define and Use Handlers in Ansible Playbooks

In Ansible, a handle is synonymous with a task, but here’s the catch – it is triggered to take action when called by another event or task it listens on. Handlers are mostly used to execute secondary tasks that proceed with the installation of a new service such as a web server or a database. These tasks include restarting or reloading services after modifications are made in the configuration files. Handlers only run then a task bears a notify directive.

Ansible Playbook file with a handler for restarting Nginx

To get a firm grasp of the role of handlers in Ansible, we will create a simple playbook file called install_nginx.yml. The playbook contains a single play that installs the Nginx webserver on a remote Ubuntu node. Right after installation, the notify directive instructs the handler to restart the Nginx service

Take careful note the ‘notify’ definition matches the name of the handler. As you can see the ‘Restart Nginx’ definition under the notify directive matches the name of the Handler in the playbook.

Now, let us run the playbook file.

$ ansible-playbook /etc/ansible/install_nginx.yml -K

From the output below, you can see that Ansible executed the task first, followed by the handler. Additionally, you can see that it recorded 2 changes which are actually the installation of Nginx and Restarting of the Nginx service which was carried out by the handler. The primary task was the installation of Nginx, while the secondary task was restarting the Nginx webserver.

Ansible Playbook file with multiple plays and handlers

Additionally, you can have a scenario where a playbook file contains multiple plays and handlers.

These are the plays we have:

  1. Installing Nginx
  2. Allowing HTTP traffic across the UFW firewall.

After the plays are executed, the notify directive calls each of the handlers to perform their tasks – restarting Nginx and reloading the UFW firewall.

In this example, the secondary tasks performed by the handlers are:

  1. Restarting the Nginx service
  2. Reloading the firewall

Let’s run the playbook once more.

$ ansible-playbook /etc/ansible/install_nginx.yml -K

Here, we have a total of four tasks. The first two are carried out by the plays and the remaining two are handled by the handlers. You can see that after runtime, the playbook recorded 4 changes which correspond to the number of operations or tasks carried out.

Conclusion

Evidently, using handlers is quite a simple and straightforward exercise. Handlers are just like tasks only that they are called by the ‘notify’ and are last to be executed in the playbook.

Similar Posts