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.ini4. Then Ansible configures the hosts:
ansible-playbook -i inventory.ini site.yml --check --diff
ansible-playbook -i inventory.ini site.yml5. 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 ansible-lint, and what does it catch?
- Can Terraform and Ansible be used together, and how would you combine them?
- How do you integrate Ansible into CI/CD and keep playbooks tested?
- What is Kustomize, and how does it differ from Helm?
- How would you orchestrate a rolling, health-checked upgrade across servers with Ansible?
- What is a kustomization.yaml, and what does it define?
- How do you handle host-specific differences across a mixed fleet?
- What is the difference between a base and an overlay in Kustomize?