In Ansible, a handler is just like any other task but only runs when called or notified. It takes action when a change has been made on the managed host. Handlers are used in initiating a secondary change such as starting or restarting a service after installation or even reloading a service after some modifications have been made in the configuration files. In this guide, we will shed more light on Ansible handlers. We will learn how to use handlers in ansible playbook.
Ansible playbook file with a handler
To better understand how Handlers work, we will take an example of a playbook file – install_apache.yml – that installs the Apache webserver and later restarts the Apache service. In the example below, the handler is notified to restart the Apache service soon after installation. This is achieved using the notify module as shown. Note that the ‘notify’ name should coincide with the handler name as pointed out, otherwise you will encounter errors in your playbook file.
--- - hosts: staging name: Install become: yes tasks: - name: Install Apache2 on Ubuntu server apt: name: apache2 state: present update_cache: yes notify: - Restart apache2 handlers: - name: Restart apache2 service: name: apache2 state: restarted
Now let’s run the playbook file.
$ ansible-playbook /etc/ansible/install_apache.yml -K
From the output, you can see the Handler being executed right after the task.
Multiple tasks with multiple handlers
Additionally, we can have several tasks calling multiple handlers. Consider the playbook file below.
Here are have 2 tasks to run:
- Installing Apache webserver
- Allowing HTTP traffic on the UFW firewall.
After the tasks are successfully executed, I have called each of the handlers with the ‘notify’ module as shown below. The first handler restarts Apache and the second one reloads the UFW firewall.
--- - hosts: staging name: Install become: yes tasks: - name: Install Apache2 on Ubuntu server apt: name: apache2 state: present update_cache: yes - name: Allow HTTP traffic on UFW firewall ufw: rule: allow port: http proto: tcp notify: - Restart apache2 - Reload ufw firewall handlers: - name: Restart apache2 service: name: apache2 state: restarted - name: Reload ufw firewall ufw: state: enabled
When the playbook file is executed, both handlers are executed by Ansible right after Apache is installed and HTTP traffic is allowed on the firewall.
The secondary actions executed by the handlers here are:
- Restarting Apache
- Enabling and reloading the firewall for the changes made to be effected.
As you have seen, handlers are just like regular tasks, only that they are referenced using a globally unique module called ‘notify’. If a handler is no notified, it fails to run. Remember that all handlers run after all the tasks have been completed.