DevOps / Ansible Interview questions
Why do we use handlers instead of regular tasks for restarts?
A service restart is disruptive - it causes a brief outage - so it should only happen when something that actually requires it has changed, like an updated configuration file. If a restart were written as a regular task, it would run every single time the playbook executes, regardless of whether anything actually changed, causing unnecessary service interruptions on every run.
By putting the restart in a handler and having the configuration-writing task notify it, Ansible only fires the restart when that specific task reports changed. If the config was already correct and nothing changed, the notify never fires and the handler never runs, keeping the service untouched. Handlers also naturally coalesce: even if several different tasks in a play all notify the same handler, it still runs only once, at the end of the play, rather than restarting the same service multiple times in a row for each individual change that triggered it.
More Related questions...