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.

Preparing for an interview?

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

← All Infrastructure as Code (Terraform, Ansible) questions