Interview › Infrastructure as Code (Terraform, Ansible)
What is a loop in Ansible, and how do you iterate over a list?
Infrastructure as Code (Terraform, Ansible) · Advanced level
Answer
A loop repeats a task for each item in a list or other iterable. It is used to install multiple packages, create users, render multiple files, or call APIs for a set of inputs. For complex data, each item can be a dictionary with named fields.
Technical explanation
loop replaces older with_items patterns in modern playbooks.
Use loop_control to customize the loop variable or label.
For nested or complex loops, consider restructuring data to keep tasks readable.
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 register, when, and loop for: What is a loop in Ansible, and how do you iterate over a list?
2. Example:
- name: Check app health
ansible.builtin.uri:
url: http://localhost:8080/health
status_code: 200
register: health
failed_when: false
- name: Restart app only when health check failed
ansible.builtin.service:
name: app
state: restarted
when: health.status | default(0) != 200
- name: Install required packages
ansible.builtin.package:
name: "{{ item }}"
state: present
loop:
- nginx
- curl
- jq
3. Run once with the service healthy and once after stopping it; confirm the conditional task changes behavior based on the registered result.
4. Use loop_control.label when iterating over dictionaries to keep output readable.
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?