Pages

Thursday, February 11, 2016

Ansible Handlers

Share it Please

Ansible as said will perform many operations on remote machine and some need a recycle or stop of service when things change. Ansible identifies what changes are done but if the changes need to be effective there needs to be some post change events. Consider when a new virtual host information is added httpd.conf, there needs a restart of the httpd service.But the most important thing at this moment is tell Ansible to restart the service. This is done via the notify action, and tasks that are called by this notify action are called handlers. So when we tell Ansible to restart the httpd service (Called as to notify ) and the task that will care of this notify action is called as handler.

Every handler task will run at the end of the playbook for example, you changed your httpd server config multiple times and you want to restart the httpd service so that the changes are applied. Restarting a Service for every change is not a good practice rather we can notify Ansible to restart httpd service on every configuration change. Ansible will then make sure no matter how many times we notify if for the restart of the Httpd service ,the httpd service is restarted only once and this is done after all others tasks are complete

Let’s see a basic example of defining a Notify and Handler,

[root@vx111a ansible]# cat apache.yml
---
- hosts: dev
  user: root
  sudo: no
  tasks:
   - name: Install Apache
     yum: pkg=httpd state=latest
     notify:
     - restart apache
   - name: ensure apache is running
     service: name=httpd state=started 
  handlers:
   - name: restart apache
     service: name=httpd state=restarted

if you check the above playbook , we have defined a task to install Httpd Package and also added a notify to restart the service. The restart is then handled by the handlers at the end.
Upon running the playbook we can see

[root@vx111a ansible]# ansible-playbook apache.yml

PLAY [dev] ********************************************************************

GATHERING FACTS ***************************************************************
ok: [172.16.202.96]

TASK: [Install Apache] ********************************************************
changed: [172.16.202.96]

TASK: [ensure apache is running] **********************************************
changed: [172.16.202.96]

NOTIFIED: [restart apache] ****************************************************
changed: [172.16.202.96]

PLAY RECAP ********************************************************************
172.16.202.96              : ok=4    changed=3    unreachable=0    failed=0  

One important thing to note is that Handlers are triggered only when a task status is changed.


More to Come ,Happy learning 

No comments :

Post a Comment