Interview › Infrastructure as Code (Terraform, Ansible)
Why do handlers run once at the end rather than immediately?
Infrastructure as Code (Terraform, Ansible) · Intermediate level
Answer
Handlers run once at the end of a play by default so multiple changes can trigger one restart instead of several restarts. They are deduplicated by handler name. If an immediate restart is required before later tasks, use meta: flush_handlers deliberately.
Technical explanation
End-of-play execution reduces service churn during a run.
meta: flush_handlers is available when later tasks depend on the handler's effect.
Handler names should be unique and stable because notify references names.
Prefer idempotent modules over shell so repeated runs are safe and change reporting is meaningful.
Separate reusable role logic from inventory-specific variables so the same automation works across environments.
Run lint, syntax checks, check mode where useful, and staged rollouts before production-wide changes.
Hands-on example
1. Use handlers correctly for: Why do handlers run once at the end rather than immediately?
2. Template a config and notify one restart:
tasks:
- name: Render nginx config
ansible.builtin.template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
validate: 'nginx -t -c %s'
notify: Restart nginx
handlers:
- name: Restart nginx
ansible.builtin.service:
name: nginx
state: restarted3. Change two template-managed files that both notify Restart nginx and observe that the handler runs once at the end.
4. If later tasks require the restarted service immediately, insert meta: flush_handlers at that point and document why.
Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.
More Infrastructure as Code (Terraform, Ansible) interview questions
- What is a handler, and how is it triggered with notify?
- What are Ansible roles, and what is the standard directory structure?
- What are Ansible modules, and why prefer them over shell commands?
- What is the order of variable precedence in Ansible at a high level?
- What is the creates argument on a command task, and how does it add idempotency?
- What are group_vars and host_vars?
- Why is a raw shell or command task not idempotent, and how do you make it safe?
- What is Ansible Vault, and how do you protect secrets with it?