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.

Preparing for an interview?

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

← All Infrastructure as Code (Terraform, Ansible) questions