Interview › Infrastructure as Code (Terraform, Ansible)
What is delegate_to, and when would you use it?
Infrastructure as Code (Terraform, Ansible) · Advanced level
Answer
delegate_to runs a task on a different host than the current inventory host. I use it for load balancer registration, API calls from localhost, database migration coordination, bastion-side checks, or centralized monitoring updates during a rollout.
Technical explanation
delegate_to: localhost is common for API calls from the control node.
delegate_facts controls whether gathered facts attach to the delegated host or original host.
Delegation is a clean way to coordinate external systems during per-host operations.
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. Orchestrate a rolling update for: What is delegate_to, and when would you use it?
2. Playbook skeleton:
- name: Rolling app upgrade
hosts: app
serial: 2
max_fail_percentage: 20
tasks:
- name: Drain host from load balancer
ansible.builtin.command: /usr/local/bin/lbctl drain {{ inventory_hostname }}
delegate_to: localhost
- name: Upgrade app package
ansible.builtin.package:
name: myapp
state: present
notify: Restart app
- meta: flush_handlers
- name: Wait for health
ansible.builtin.uri:
url: http://{{ inventory_hostname }}:8080/health
status_code: 200
retries: 12
delay: 5
register: health
until: health.status == 200
- name: Add host back to load balancer
ansible.builtin.command: /usr/local/bin/lbctl enable {{ inventory_hostname }}
delegate_to: localhost3. Test against a staging group with serial: 1, then increase batch size after measuring recovery time.
4. Confirm a failed health check stops the rollout before most hosts are touched.
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 max_fail_percentage, and how does it protect a rollout?
- What is the difference between Ansible roles and collections?
- What is the serial keyword, and how does it enable rolling updates?
- What is a Jinja2 template, and how is it used in Ansible?
- What is a loop in Ansible, and how do you iterate over a list?
- How do you run an Ansible playbook in check (dry-run) mode?
- What is the when clause, and how do you write conditional tasks?
- What is the difference between state: present and state: latest, and the risk of latest?