Interview › Infrastructure as Code (Terraform, Ansible)
What is the order of variable precedence in Ansible at a high level?
Infrastructure as Code (Terraform, Ansible) · Intermediate level
Answer
At a high level, Ansible variable precedence means more specific and later sources override broader defaults. Role defaults are low precedence, inventory and group variables are in the middle, play/task vars are higher, and extra vars are near the top. I avoid relying on obscure precedence and keep variable ownership clear.
Technical explanation
Extra vars are powerful and should be controlled in CI because they can override nearly everything.
Role defaults are the safest place for configurable defaults.
Good naming conventions reduce accidental variable collisions.
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. Model variables and facts for: What is the order of variable precedence in Ansible at a high level?
2. Create inventory variables:
group_vars/web.yml:
app_port: 8080
package_name_by_os:
RedHat: httpd
Debian: apache2
host_vars/web1.yml:
app_port: 9090
3. Use facts and variables in a task:
- name: Install OS-specific web package
ansible.builtin.package:
name: "{{ package_name_by_os[ansible_facts['os_family']] }}"
state: present
when: ansible_facts['os_family'] in package_name_by_os4. Run ansible-playbook site.yml -e app_port=7070 in a lab to see extra vars override lower-precedence values.
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 roles, and what is the standard directory structure?
- What are group_vars and host_vars?
- Why do handlers run once at the end rather than immediately?
- What is Ansible Vault, and how do you protect secrets with it?
- What is a handler, and how is it triggered with notify?
- What is the difference between a variable and a fact?
- What are Ansible modules, and why prefer them over shell commands?
- How does Ansible gather facts, and how do you use them in conditionals?