Handlers in Ansible

Handlers in Ansible

Hi there! So today we are going to see how ansible uses the concept of handler to make configuration management more efficient process. So let's get started.

Problem

Whenever we run the web server playbook in ansible we change lot of configurations , so we need to restart the web server so that the new configurations are pushed to the server. So in ansible service module performs this task BUT if we look at this code

- name : Start web server
  service : 
      name : httpd
      state : started

This will just check if the web server is running or not it will not restart the server if conf file are changed. So we can modify it like this.

- name : Start web server
  service : 
      name : httpd
      state : restarted

Now this will restart the services but it will restart the services every time the playbook is run no matter weather conf files are changed or not. So this is inefficient use of resources.

How Ansible solves this problem ?

Now to solve this problem there are two ways :

  • First way is to check if the conf files have changed and then restart the web server based on that. So we can do this by using register and when keywords in ansible

Screenshot (1018).png

Here's my playbook

Now after running we got what we wanted.

VirtualBox_Ansible Controller Redhat_21_12_2020_17_41_58.png

  • This above approach works but it is not Ansible way of doing this thing.That brings us to the second way which is using Handlers.

Handlers are just like normal tasks in an Ansible playbook but they run only when if the Task contains a “notify” directive. It also indicates that it changed something.

This is how it looks.You can check the whole code here

Screenshot (1019).png

Now let's run the playbook.

VirtualBox_Ansible Controller Redhat_21_12_2020_17_46_04.png

Now if we again run the playbook you will see the difference.

VirtualBox_Ansible Controller Redhat_21_12_2020_18_48_57.png

So this way we can solve the above problem and make our configuration management efficient and idempotent using Handlers in Ansible.

That's it for this one.See you next time ...!!

Did you find this article valuable?

Support Written Wisdom by becoming a sponsor. Any amount is appreciated!