Make Web Server Idempotent With Ansible

What is idempotence ?
In general, idempotence is “the property of certain operations in mathematics and computer science that can be applied multiple times without changing the result beyond the initial application”. For Ansible it means after 1 run of a playbook to set things to a desired state, further runs of the same playbook should result in 0 changes.
Let’s understand the importance of idempotence why it’s required !!
Ex. HTTPD Service is not idempotence
To understand this concept first install the Apache webserver to the target node. Let’s say my requirement is to change the port no and Document root of apache webserver.
We already know that by default DocumentRoot of Apache Webserver is /var/www/html and Port no is 80. Let’s change the document root and port no.
Note -: To change the above thing we need to go to the particular folder i.e. /etc/httpd/conf.d/

As it’s seen in the above screen shot that my all.conf file and it’s location

Here We are Changing the Port and DocumentRoot after saving these file we required to restart the httpd service.
systemctl restart httpd -: command to restart service

see port no 8080 is acting as one of the port for httpd.
LET’S GET BACK TO ANSIBLE
When using ansible to send configuration file from controller node to target node we need to restart the service. So we’ll define state of service as restarted.

the challenge comes up after u’ll be running same playbook second time as the state is restarted it will always be running now matter the change is there or not ( idempotency). Why should u care about this part ?? Because every time u restarting the service it’s consuming resources from the target node.
Solution
1.Using concept of handlers __ 2. Conditional statements
I’ll be using handlers concept to solve this challenge.
What is Handlers??
Sometimes you want a task to run only when a change is made on a machine. For example, you may want to restart a service if a task updates the configuration of that service, but not if the configuration is unchanged. Ansible uses handlers to address this use case. Handlers are tasks that only run when notified. Each handler should have a globally unique name.
So we’ll be restarting service only if there is any change in the configuration file.


As u can see if there is no change in copy or template module service function won’t work know let’s see the document root data.


We able to change the port and document root and understand why idempotence is important how to achieve this using concept of handlers.