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: 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 are Ansible modules, and why prefer them over shell commands?
- Why do handlers run once at the end rather than immediately?
- What is the creates argument on a command task, and how does it add idempotency?
- What are Ansible roles, and what is the standard directory structure?
- Why is a raw shell or command task not idempotent, and how do you make it safe?
- What is the order of variable precedence in Ansible at a high level?
- What is idempotency in Ansible, and why does it matter?
- What are group_vars and host_vars?