Interview › Infrastructure as Code (Terraform, Ansible)
What is a handler, and how is it triggered with notify?
Infrastructure as Code (Terraform, Ansible) · Intermediate level
Answer
A handler is a special task that runs only when notified by a changed task. For example, template a config file and notify Restart nginx only if the template changed. This avoids unnecessary restarts and ties operational actions to real changes.
Technical explanation
Handlers are normal tasks listed under handlers but triggered by notify.
They run only when the notifying task reports changed.
Multiple tasks can notify the same handler and it will still run once by default.
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: What is a handler, and how is it triggered with notify?
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?