Solving Problem Of Non-Idempotence Nature Of Some Tasks In Ansible PlayBook

Monil Goyal
3 min readMar 20, 2021

--

Problem Statement:

Restarting httpd Service is not idempotence in nature and also consume more resources.

What is idempotent?

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 ansible-playbook, the operation which is idempotence run only when the result is different or there is some change in the result w.r.t to the previous one.

This saves our time and resources to configure the operating system.

To solve the problem of the non-idempotence nature of restart service, We can use handlers in ansible PlayBook.

Handlers in Ansible PlayBook

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.

Use of Notify keyword

We use notify keyword with the task on executing of which we want to execute the handlers and its values is the name of tasks in the handler block.

Rectifying the above-mentioned problem

let’s see what the problem is.

→ ansible-playbook

ansible-playbook

→ configuration file to copy in httpd webserver

Here, I selected 81 port number to run the webserver

The yellow colour indicates all the tasks run properly with no error.

Now I again run the playbook with same port number.

The green colour indicates the task is already done.

But the “start service” task is not showing idempotence nature even the configuration file is same.

Restarting httpd service may have bad impact on our performance, so it is not good practice to restart the service every time when ansible-playbook is run.

We need to restart the service only when the configuration file changes.

To solve this problem we use handlers.

- hosts: httpd
vars_prompt:
name: port_no
prompt: "port no of server to listen?"
private: no
tasks:
- name: "download httpd package"
package:
name: 'httpd'
state: present
- name: 'copy webpages'
copy:
dest: '/var/www/html/index.html'
content: 'listen on {{port_no}}'
- name: 'copy configure file'
template:
dest: '/etc/httpd/conf.d/server.conf'
src: '/root/server.conf'
notify: 'start service'
handlers:
- name: 'start service'
service:
name: 'httpd'
state: 'restarted'

whenever the task “copy configure file” executes notify keyword acknowledge the handlers to execute.

Now see, restart task is not executing on selecting port 80

But on selecting port number 8080, it is executing because the configuration file also changed.

So handlers are useful in this scenario.

Thanks, for reading…

Keep Learning Keep Sharing !!!

--

--