DevOps / Ansible Interview questions
How do you use handlers in Ansible?
A handler is a task that only runs when explicitly triggered by another task's notify directive, and typically only when that task actually reports a change. Handlers are the standard way to express "restart this service, but only if its configuration actually changed."
tasks: - name: Update nginx config ansible.builtin.template: src: nginx.conf.j2 dest: /etc/nginx/nginx.conf notify: Restart nginx handlers: - name: Restart nginx ansible.builtin.service: name: nginx state: restarted
Handlers are defined much like normal tasks but live in a separate handlers section (or a role's handlers/main.yml), and by default they run once, at the end of the play, after all regular tasks have completed - even if multiple tasks notify the same handler during the run, it still only fires a single time.
More Related questions...