Making restarting the service idempotent using Ansible playbook

Muhammad Tabish Khanday
3 min readJul 8, 2021

Challenge:

Restarting HTTPD service is not idempotence in nature and also it consumes more resources. How can we rectify this challenge in Ansible Playbook???

Idempotency in Ansible

Ansible’s philosophy is that playbooks (whether for server provisioning, server orchestration, or application deployment) should be declarative. This means that writing a playbook does not require any knowledge of the current state of the server, only its desirable state.

The principle that enables Ansible to be declarative and yet reliable is idempotence, a concept borrowed from mathematics. An idempotent operation is one that can be applied multiple times without changing the result beyond the initial application, such as multiplication by zero. Most of the Ansible modules are idempotent. 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.

Now, this is the ansible-playbook for installing httpd web server and starting it’s services,

After running the playbook

Clearly, the service task changed state and again restarted i.e this task doesn’t support idempotence. Hence, It will restart every time we run the playbook and thus will consume more system resources.

Let’s overcome this challenge.

Sometimes you want a task to run only when some kind of change is made. For example, you may want to restart the httpd service only when the webpage code is changed. Ansible has a concept of Handlers to address this use case.

Handlers are tasks that only run when notified.

Changed code after using Handlers:

Let’s run the playbook again:

So here this time handler won’t run as no changes are made.

Now let’s make some changes to the index.html page and run the playbook again to check if the handler was called and the httpd service was restarted.

As you can see that handler has run as changes were made. And thus we rectified the challenge.

That’s all for today! I’ll be back with some new articles very soon, thanks! 🤗

Muhammad Tabish Khanday

LinkedIn: https://www.linkedin.com/in/mtabishk/

--

--