Ansible logoAnsible/
ANS-E5003

Tasks that run when changed should likely be handlersANS-E5003

Minor severityMinor
Anti-pattern categoryAnti-pattern

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