ANSIBLE : Handlers
PROBLEM :
We all know that ansible is famous for it's idempotency.
But if we configure some service and if we change anything in it's configuration file, then we need to restart that service.
The problem is : if configuration file is unchanged, then?
Then also our ansible task will run and restart service unnecessarily.
In this case, ansible is not working as idempotent.
Our service will restart every time we run the playbook, even if configuration file is not updated.
SOLUTION : HANDLERS
We can use Handlers in Ansible to tackle this problem.
Handlers are just like a normal task.
Handlers will perform an action when listens for a notify event. If nothing notifies a handler, it will not run. Regardless of how many tasks notify a handler, it will run only once, after all of the tasks completed in a particular play.
To know more about ansible and it's playbook, check my this blog : ANSIBLE : How Industries are solving Challenges using Ansible
ANSIBLE PLAYBOOK USING HANDLERS :
This is the playbook I've created -
This playbook can do following things:
- Mount dvd
- Configure yum
- Install apache web server
- Create new Document root
- Configure httpd for new Document root and port number
- Upload webpage
- Start httpd service
- Allow port in firewall
- Restart httpd if configuration file updated
This is the code written in YAML format in ansible Playbook :
I've used variable concept to make is Dynamic. For this i've used vars_files module. Using this module, we can create a separate file for variables so that if we need to change some variable, we can do that without changing anything in main file.
Then I deleted the folder created in Configuration file of target node then run the playbook :
Here you can see, something has changed as yellow colored output came up and changed=2 .
It's updating the configuration file.
And we need to restart service if something changed in configuration file. So it's restarting service using Handlers.
You can see HANDLER is running this time.
Then again i run the playbook in same controller node :
This time you can see HANDLER is not running.
That means handler is only running when notified, when the task containing a “notify” directive is running.
That means handler is only running when notified, when the task containing a “notify” directive is running.
Hope you liked my blog and it would be useful for you :)
Comments
Post a Comment