Idempotence using Ansible Handlers

In Ansible, idempotence is the property of a task or command that can be run multiple times without changing the end state of the system. This means that running the same task or command multiple times should have the same effect as running it once.

Ansible handlers are a way to run tasks in response to specific events or changes in the system. They are defined in the playbook and are triggered by a notify directive in another task. Handlers are only run once, even if multiple tasks notify them. This makes them an excellent tool for achieving idempotence in Ansible.

Here is an example of how you might use a handler to ensure idempotence:

- name: Install Apache web server

  yum:

    name: httpd

    state: present

  notify:

    - restart apache

 

- name: Restart Apache web server

  service:

    name: httpd

    state: restarted

  handler: restart apache

In this example, the first task installs the Apache web server package using the yum module. The notify directive tells Ansible to trigger the "restart apache" handler after the task completes. The second task is the handler itself, which uses the service module to restart the Apache web server.

Because the handler is only run once, regardless of how many tasks notify it, this ensures that the Apache web server is only restarted once, even if the "Install Apache web server" task is run multiple times.

In this way, Ansible Handlers play a major role in achieving the idempotence in playbooks.

 

Previous Post Next Post