Restarting HTTPD Service is not Idempotence in nature and also Consumes more Resources — A way to rectify this challenge in Ansible playbook

Ananya Sharma
2 min readMar 26, 2021

--

As you all know, restarting HTTPD service is not idempotence in nature and also consumes more resources. So, here is away to rectify this challenge in Ansible playbook using handlers.

What are handlers in Ansible?

Handlers are just like normal tasks in an Ansible playbook but they run only when if the task contains a “notify” directive. It also indicates that it changed something.

By default, handlers run after all the tasks in a particular play have been completed. This approach is efficient, because the handler only runs once, regardless of how many tasks notify it. For example, if multiple tasks update a configuration file and notify a handler to restart Apache, Ansible only bounces Apache once to avoid unnecessary restarts.

Use the following code for the same:-

- hosts: all
tasks:
name: "Changing Port Number"
lineinfile:
path: /etc/httpd/conf/httpd.conf
regex: "[lL]isten 80"
line: "Listen 81"
notify: "Restart HTTPD"
handlers:
name: "Restart HTTPD"
service:
name: "httpd"
state: "restarted"

Now, run the playbook using the following command:-

ansible-playbook playbook_name.yml

Here, you can see that the HTTPD service restarted because we had changed the port number.

Now, if we again run the playbook, the HTTPD service won’t restart because the port number is the same as the previous one.

Hence, we can conclude that the restarting HTTPD service is idempotence in nature in the Ansible playbook.

Thank you :)

--

--

No responses yet