Ansible

Ansible

Made by DeepSource

Tasks that run when changed should likely be handlers ANS-E5003

Anti-pattern
Minor

If a task has a when: result.changed setting, it is effectively acting as a handler.

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.

Bad practice

- name: Template configuration file
  ansible.builtin.template:
    src: template.j2
    dest: /etc/foo.conf
  register: copyTemplate

- name: Restart memcached
  ansible.builtin.service:
    name: memcached
    state: restarted
  when: copyTemplate.changed

- name: Restart apache
  ansible.builtin.service:
    name: apache
    state: restarted
  when: copyTemplate.changed

Recommended

- name: Template configuration file
  ansible.builtin.template:
    src: template.j2
    dest: /etc/foo.conf
  notify:
    - Restart memcached
    - Restart apache

  handlers:
    - name: Restart memcached
      ansible.builtin.service:
        name: memcached
        state: restarted

    - name: Restart apache
      ansible.builtin.service:
        name: apache
        state: restarted

References

[1] [Ansible documentation](https://docs.ansible.com/ansible/latest/userguide/playbookshandlers.html).