Making Idempotence in Ansible more Effective

Problem Statement: Restarting HTTPD Service is not idempotence in nature and also consume more resources suggest a way to rectify this challenge in Ansible playbook


  1. The Playbook Should install httpd package on the OS

What is Idempotency ?

Idempotency is basically an action which, when performed multiple times, has no further effect on its subject after the first time it is performed.

In the Ansible the Ansible modules show the similar nature if the desired state mentioned in them does not match the actual state in the managed node then only the changes will be done otherwise there will be no changes done.

Solution 1:


In the code mentioned above there are basically 3 modules used package module (Installs, upgrade and removes packages), copy module (The copy module copies a file from the local or remote machine to a location on the remote machine) and service module (Start, stop or restart a service on a remote host)

It is necessary to restart the httpd services whenever any changes in the configuration file is done. but here in this code we have not mentioned any condition such. We are restarting the services always so this consumers resources unnecessarily.

Solution 2:

So in this part we will try to solve the challenge faced in Solution 1

httpd configuration file (Here I have used port 8080 as httpd port)

In the above mentioned code we have used some keywords like register and when. register is a keyword is a way to capture the output from task execution and store it in a variable. when is a keyword in ansible used to mention the conditions if the condition is satisfied then only the block of code will be executed or else it will be skipped.

Now Lets Run the playbook. I have launched an instance over the AWS cloud we will be using it as a Managed Node

Lets First Try to ping it via ansible using ansible ping module

Now Lets Run the playbook

According to the conditions the Skip operation has been done successfully also the Web App is configured properly to port 8080

Now lets again do some changes in web pages and configuration file and see whether start operation will be done again or not

httpd configuration file and index file(Here I have used port 1234 as httpd port)

So the Start operation didn’t run again but this time the restart operation ran. So our code is working properly. Also after first execution of playbook if we run playbook without any changes it will not restart services. now resources will be used properly without unwanted consumption.

GitHub Link:

Thankyou For Reading

Any query and suggestion are always welcome- Gaurav Pagare

Arth Learner @ LW INDIA