Interview › Infrastructure as Code (Terraform, Ansible)
What is a register, and how do you use the result of one task in another?
Infrastructure as Code (Terraform, Ansible) · Advanced level
Answer
register stores the result of a task in a variable. The result can include stdout, stderr, return code, changed status, skipped status, and module-specific fields. I use it to make later tasks conditional on real command or module output.
Technical explanation
Registered variables are scoped to the host executing the task.
Check stdout_lines for line-oriented output and rc for command status.
Registered results are commonly combined with when, changed_when, and failed_when.
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 register, and how do you use the result of one task in another?
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
- jq3. 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 the when clause, and how do you write conditional tasks?
- What is a loop in Ansible, and how do you iterate over a list?
- What is the serial keyword, and how does it enable rolling updates?
- What is max_fail_percentage, and how does it protect a rollout?
- What is delegate_to, and when would you use it?
- What is the difference between Ansible roles and collections?
- What is a Jinja2 template, and how is it used in Ansible?
- How do you run an Ansible playbook in check (dry-run) mode?