Ansible — restarting a service with idempotency

Ansible and httpd integration

Bhavesh Kakrotra
2 min readMar 23, 2021

When we have to create playbooks in which we need to restart services they restart every time we run the playbook. To avoid this we need to make our playbooks idempotent with the use of handlers.

Source: Glossary — Ansible Documentation

Here we will create a playbook which only starts/restarts a service only when there is a change.

First create an ansible.cfg file that looks something like this:

[defaults]
inventory = ./inventory
host_key_checking = False
remote_user = root

Then create your inventory which should look similar to this:

[mywebserver]
192.168.43.192 ansible_ssh_pass=redhat

In my case I have two jinja templates in the templates directory.

[root@localhost templates]# ls
hello.conf index.html
[root@localhost templates]# cat hello.conf
Listen {{ port_no }}
<virtualhost {{ ip }}>
DocumentRoot {{ document_root }}
</virtualhost>
[root@localhost templates]# cat index.html
This is comming from {{ ansible_distribution }} {{ ansible_distribution_version }}

Now begin writing the playbook. It should look like:

And now when you run this playbook twice, you will find that the playbook is completely idempotent.

And finally this is our website:

Feel free to contact on my LinkedIn.

--

--