Interview › Infrastructure as Code (Terraform, Ansible)
When would you choose Ansible over Terraform and vice versa?
Infrastructure as Code (Terraform, Ansible) · Advanced level
Answer
I choose Terraform when I need to provision and own infrastructure lifecycle through cloud APIs. I choose Ansible when I need to configure systems, orchestrate tasks, or perform procedural changes across hosts. Terraform is best for desired infrastructure graph; Ansible is best for operational automation and host configuration.
Technical explanation
The dividing line is lifecycle ownership: Terraform owns cloud objects; Ansible configures or orchestrates running systems.
Terraform should not be used as a general remote command runner.
Ansible should not replace Terraform for complex graph-based cloud dependencies.
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. Combine Terraform and Ansible for: When would you choose Ansible over Terraform and vice versa?
2. Terraform provisions instances and outputs inventory data:
output "web_private_ips" { value = aws_instance.web[*].private_ip }
3. CI writes a temporary inventory from Terraform output:
terraform output -json web_private_ips | jq -r '.[]' | awk '{print "web ansible_host="$1}' > inventory.ini
4. Then Ansible configures the hosts:
ansible-playbook -i inventory.ini site.yml --check --diff
ansible-playbook -i inventory.ini site.yml
5. Document that Terraform owns cloud objects and Ansible owns host configuration to prevent dual ownership.
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?