How to hold Idempotence property of Ansible while restarting the HTTPD service?

→Restarting httpd with idempotence nature in ansible by using a keyword←

Hola Connections….🙋!!

In this article, we will discuss How to gain idempotence in ansible while restarting the HTTPD service💫. So, let’s begin….✨

👉 What do you mean by Idempotency ?

An operation is idempotent if the result of performing it once is exactly the same as the result of performing it repeatedly without any intervening actions.✨

In other words, In mathematics, idempotency can be seen when we multiply x by 1. It doesn’t matter how many times we perform this operation the result (x) is the same.


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

🔸Here the challenge is —

Whenever there is some change in configuration file and in the code, the HTTPD apache webserver’s service has to be restarted and for this , we generally use “restarted” keyword in the state but if, even there are no changes made to the conf. file, still it restart the webserver(or HTTPD service) by this process whenever we run the playbook. And the challenge is we only wants to restart the service when there are some changes in the code or in conf. file such as changing document root, etc.

☑️ Solution: “Use of handlers and notify keyword”

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.

Sometimes you want a task to run only when a change is made on a machine. For example, you may want to restart a service if a task updates the configuration of that service, but not if the configuration is unchanged. Ansible uses handlers to address this use case. Handlers are tasks that only run when notified. Each handler should have a globally unique name.

👉 For example:- Here is my playbook ‘httpd_service_restart.yml’

- hosts: all
- name: "document_root"
prompt: "Enter your document root name"
private: no
- name: "http_portno"
prompt: "Enter the port no"
private: no
- name: Install httpd software
name: httpd
state: present
register: z
- name: Creating folder
name: "{{ document_root }}"
state: directory
- name: Copy the configuration file
dest: "etc/httpd/conf.d/https.conf"
src: "webs.conf"
when: z.rc==0
notify: Restart service
- name: Copy html code to document root
dest: "{{ document_root }}"
src: "web.html"
- name: Start httpd service
name: "httpd"
state: started
enabled: yes
- firewalld:
port: "{{ http_portno }}/tcp"
state: enabled
permanent: yes
immediate: yes
- name: Restart service
name: "httpd"
state: restarted

Thus, Task completed successfully🎉 !


GitHub link:-

Aeromodeller|Passionate|Technoholic|Learner|Technical writer