Making Httpd service Idempotent in Ansible playbook.

Arjun Singh
3 min readApr 11, 2021

This article will give you an idea of how you can write ansible plays more effectively in terms of optimization.

Problem Statement:

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

Given Scenario

Suppose your goal is to configure webserver on a number of managed nodes. And you want to customize the httpd configuration to port 8080 instead of 80 and Document Root to some other folder, rather than /var/www/html.

For this, you’ll need to write appropriate tasks in the playbook and later restart your httpd server.

But what about those managed nodes which are already running with the required configuration? When you will run the playbook, although idempotence will be applied to the tasks where you will do the configuration, the part where you restart the server will not follow idempotence and will lead to restarting of service even when it is not required.

We have to come up with a solution to provide idempotence to restarting the httpd server.

Initial playbook without idempotence.

Running the playbook on node which is already configured:

We see that the service task is not idempotent, whether we change the configuration or not, it runs this task anyways.


Although there could be multiple other ways such as Conditional tasks using “when” and “register” keywords. But the most efficient way is to use Notify and Handler.

We’ll bind the service task in a box and ask the template/copy task to notify the box of service task to run. This box is the handler. The handler is like a normal task but it is put in a separate section of code.

You can compare Handler to a function definition that only runs when it is called. Hence, idempotence can be applied to the Restart of the service task.

Let’s see the code.

Now, on running the code on an already configured managed node, we get full idempotence:

If we run the playbook for some not-configured node, then only the service task will run.

Handler runs only when the configuration is changed.

So, this is how we can solve this Idempotence problem using Notify and Handler.

Thank You for reading… :)