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: restarted
3. 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 Infrastructure as Code, and what problems does it solve over click-ops?
- What is the difference between declarative and imperative IaC, and where do Terraform and Ansible fall?
- What is the difference between configuration management and provisioning?
- What is Terraform, and what is the core plan/apply workflow?
- What does terraform init do?
- What is the Terraform state file, and why is it critical?
- Why should state be stored remotely, and what backend would you use on AWS?
- What is state locking, and why does it matter for teams?