Idempotency in Ansible

In general, idempotence is “the property of certain operations in mathematics and computer science that can be applied multiple times without changing the result beyond the initial application”. For Ansible it means after 1 run of a playbook to set things to the desired state, further runs of the same playbook should result in 0 changes. In simplest terms, idempotency means you can be sure of a consistent state in your environment.

In simpler words, Ansible won't perform a task repeatedly. For example, we write a playbook to create a directory but if the directory is already created then it won't recreate it, it would skip that part. But sometimes some modules don't provide this facility. For example, shell/ command module. Every time the playbook is run Ansible will re-run the command. Similarly, the restart argument in the services module. To achieve idempotence in these cases we need to add some more blocks of code. This is where we use handlers.

Sometimes we 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.

- name: "Copying the files"
template:
dest: "/var/www/html"
content: "This is test!!"
notify:
- "Restart httpd Services"
handlers:
- name: "Restart httpd services"
service:
name: "httpd"
state: restarted

Here, we only need to restart the httpd services only if the template module runs otherwise we don't want the httpd services to be restarted. So if the template module runs then the notify command will notify the handler to run the service module and the services will be restarted.

NOTE: One playbook can have multiple notifiers and handlers. There is no limit to it.

That’s all,

Thank you for reading!!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store