Interview › Infrastructure as Code (Terraform, Ansible)
Can Terraform and Ansible be used together, and how would you combine them?
Infrastructure as Code (Terraform, Ansible) · Advanced level
Answer
Terraform and Ansible work well together. Terraform can provision infrastructure and output inventory or endpoints. Ansible can then configure hosts or deploy software. The key is to keep ownership boundaries clear so both tools do not fight over the same setting.
Technical explanation
Use Terraform outputs to produce dynamic inventory or publish endpoints.
Run Ansible after Terraform only when infrastructure is ready and reachable.
Avoid dual ownership of tags, security groups, config files, or Kubernetes fields.
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: Can Terraform and Ansible be used together, and how would you combine them?
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?