Making Restart of Httpd Service Idempotent in Ansible Playbook
Restarting httpd service is not idempotent in nature and consumes more resources.In this blog,we will see how to rectify this challenge in Ansible plabook
General Approach for Restarting httpd services
The general approach of restarting httpd services in Ansible plabook is to use the service module inside the tasks block and give the state argument as restarted.
#service module inside the tasks block
tasks:
- name: service httpd
service:
name: "httpd"
state: restarted
But in this approach,the httpd service is always restarted when the playbook is executed and the idempotence nature is lost.
To solve this challenge,we can use the concept of notify and handler in Anisble Playbook.
Restarting Httpd services using Notify and Handler
In this,there is a notifying task,which whenever produces a change in the output,notifies another task to run itself,which is called the handler.Thus,the task inside the handler block is executed only when the notifying task produces a changed output.
tasks:
- name: Copy conf file
template:
src: "local_conf.conf.j2"
dest: "/etc/httpd/conf.d/web.conf"
notify: service httpd #Whenever the conf file is changed it
notifies the task in handler to run#The task inside handler runs only when notified
handlers:
- name: service httpd
service:
name: "httpd"
state: restarted
Thus,whenever there is a change in the configuration file,it notifies the task inside handler with name service httpd
Thus,the httpd service is only restarted whenever there is a change in the configuration file.Hence,we have achieved idempotence in restarting httpd services.
Thank You!!