Idempotence in Ansible

Nishant Saini
3 min readMay 18, 2021

--

One of the feature of Ansible is Idempotence

In general, idempotence is “the property of certain operations that can be applied multiple times without changing the result beyond the initial application”.

For Ansible it means after first run of a playbook to set things to a desired state, further runs of the same playbook should result in 0 changes.

For example, if one of the tasks is to create a directory on the server, then the directory will be created if and only if it does not already exist.

But some of the modules in Ansible don’t have Idempotence feature, for example “command” module.

Task Description:

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

Explanations:

Let’s say we created a playbook to configure httpd webserver on the target node and we have also done some changes in the configuration file of httpd (i.e we changed the port no. of httpd from 80 to 8080), so we have to restart the services of httpd, so the final playbook looks something like:

Now, if we run the playbook, it will configure the webserver on target node, but the challenge is that “restarted” option of the “service” module doesn’t work on the concept of idempotence, means if we run the same playbook again it will again restart the services of httpd even if services of httpd are already running and we hadn’t changed anything in the configuration file of httpd now.

We want to achieve idempotence i.e we want restart will only restart the services of httpd again only if we have changed something in the configuration file of httpd(as services of httpd are already running).

For this we can take help of “notify” and “handlers”.

So to achieve idempotence we can make ansible-playbook as:

Now , the module that is placed inside handlers will run only when notify will ask it to run and notify will notify only when we change something inside configuration file of httpd .

So, using this approach we can achieve idempotence in httpd.

--

--

Nishant Saini
Nishant Saini

Written by Nishant Saini

0 Followers

RedHat Certified Engineer (RHCE) | AWS Academy Graduate | DevOps Enthusiast

No responses yet