Compare Ansible vs Terraform for infrastructure management. When would you use each, and can they work together?
Quick Answer
Terraform: declarative, state-managed, best for provisioning cloud infrastructure. Ansible: procedural, agentless, best for configuration management and application deployment. Together: Terraform provisions, Ansible configures.
Detailed Answer
Terraform Strengths
- Declarative: describe desired state, Terraform figures out how to get there - State file tracks what exists — knows what to create, update, or destroy - Excellent for cloud resource provisioning (VPCs, instances, databases) - Plan/apply workflow with drift detection - Provider ecosystem for every cloud and SaaS service
Ansible Strengths
- Procedural: step-by-step instructions executed in order - Agentless: uses SSH, no software to install on targets - Excellent for configuration management (packages, files, services) - Application deployment and orchestration - Ad-hoc commands for quick tasks - Jinja2 templating for dynamic configs
When Ansible is wrong
- Managing cloud infrastructure lifecycle (no state tracking) - Ensuring resources are destroyed when removed from code
When Terraform is wrong
- Installing packages, configuring services, managing files on servers - Running deployment scripts, health checks, rolling restarts
Together (common pattern)
1. Terraform provisions: VPC, EC2 instances, RDS, load balancers 2. Terraform outputs instance IPs to a dynamic inventory file 3. Ansible configures: installs packages, deploys application, starts services 4. CI/CD: terraform apply then ansible-playbook deploy.yml
Code Example
# Terraform provisions infrastructure
resource "aws_instance" "web" {
count = 3
ami = "ami-0abcdef1234567890"
instance_type = "t3.medium"
tags = { Name = "web-${count.index}" }
}
# Output IPs for Ansible
output "web_ips" {
value = aws_instance.web[*].private_ip
}
# Generate Ansible inventory from Terraform
resource "local_file" "ansible_inventory" {
content = templatefile("inventory.tpl", {
web_servers = aws_instance.web[*].private_ip
})
filename = "../ansible/inventory/hosts"
}
# Ansible configures the servers
# deploy.yml
- hosts: webservers
become: true
roles:
- common
- nginx
- app_deploy
# CI/CD pipeline
# 1. terraform init && terraform apply -auto-approve
# 2. ansible-playbook -i inventory/hosts deploy.ymlInterview Tip
Show you understand the fundamental difference: Terraform is declarative with state, Ansible is procedural without state. The combined pattern (Terraform provisions, Ansible configures) is the pragmatic answer.