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
Here's my playbook
Now after running we got what we wanted.
- 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
Now let's run the playbook.
Now if we again run the playbook you will see the difference.
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 ...!!