Creating Handlers in Ansible
Introduction
Handlers in Ansible are special tasks that only run when notified by other tasks. They are typically used to perform actions such as restarting a service after a configuration change. Handlers ensure that these actions are performed at the correct time and only when necessary.
Understanding Handlers
Handlers are similar to regular tasks but are defined in a special section called handlers. They are triggered using the notify directive within tasks. If multiple tasks notify the same handler, it will only run once at the end of the playbook execution.
Creating a Handler
To create a handler, you need to define it in the handlers section of your playbook or role. Here’s a simple example of a handler that restarts the Apache service:
handlers:
- name: restart apache
service:
name: apache2
state: restarted
Using Handlers
To use a handler, you notify it from a task. Here’s an example where a task that updates the Apache configuration file notifies the restart apache handler:
tasks:
- name: update apache config
copy:
src: /path/to/httpd.conf
dest: /etc/apache2/httpd.conf
notify:
- restart apache
Complete Example
Here’s a complete example of a playbook that updates the Apache configuration and uses a handler to restart the service:
---
- name: Update Apache configuration
hosts: webservers
tasks:
- name: update apache config
copy:
src: /path/to/httpd.conf
dest: /etc/apache2/httpd.conf
notify:
- restart apache
handlers:
- name: restart apache
service:
name: apache2
state: restarted
Testing the Handler
To test the handler, you can run the playbook using the following command:
Assuming your inventory file and playbook are set up correctly, the handler should be triggered when the Apache configuration changes, and the service should be restarted.
Conclusion
Handlers are a powerful feature in Ansible that allow you to perform actions at the right time and only when necessary. By understanding how to create and use handlers, you can make your playbooks more efficient and reliable.
