Handlers-Ansible
In Ansible, handlers are special tasks that run only when notified by other tasks. They are typically used for operations that need to occur after a change has been made, such as restarting a service after its configuration file has been modified.
Defining and Using Handlers
handlers:
- name: restart apache
service:
name: httpd
state: restarted
Notify a Handler: Tasks that can trigger handlers include a notify directive, specifying which handlers to trigger when the task reports a changed status.
tasks:
- name: copy the httpd configuration file
copy:
src: /path/to/httpd.conf
dest: /etc/httpd/conf/httpd.conf
notify: restart apache
Example Playbook with Handlers
Here's a complete example demonstrating the use of handlers in a playbook:
---
- hosts: webservers
become: yes
tasks:
- name: install httpd
yum:
name: httpd
state: present
- name: copy the httpd configuration file
copy:
src: /path/to/httpd.conf
dest: /etc/httpd/conf/httpd.conf
notify: restart apache
- name: start httpd service
service:
name: httpd
state: started
handlers:
- name: restart apache
service:
name: httpd
state: restarted
Key Points
Thank You for reading.