Terraform vs Ansible
EasyTerraformAnsibleIaC
What's the difference between Terraform and Ansible, and when do you use each?
TL;DR
Terraform is for provisioning infrastructure: it declares the desired cloud resources (networks, databases, clusters, DNS), keeps state, and computes a plan to create, change or destroy them. Ansible is for configuring machines: it runs tasks over SSH to install packages, edit files and manage services on servers that already exist, and needs no agent or state file. Short version: Terraform creates the servers, Ansible configures what runs on them.
Key points
| Terraform | Ansible | |
|---|---|---|
| Main job | Provisioning (cloud APIs) | Configuration management (OS level) |
| Style | Declarative, with a plan | Procedural playbooks of mostly idempotent modules |
| State | State file | None; checks the live system each run |
| Language | HCL | YAML |
| Typical targets | AWS/GCP/Azure, Kubernetes, SaaS APIs | Linux/Windows hosts, network devices |
- In container- and Kubernetes-based stacks, Ansible's role shrinks: images are built by Dockerfiles and apps are configured by Kubernetes manifests. It's still common for VMs, on-prem servers, and network gear.
- Immutable infrastructure (bake images with Packer, replace instead of patch) is often preferred to configuring live servers.
- Alternatives: Pulumi or the AWS CDK (IaC in real programming languages), OpenTofu (an open-source Terraform fork), Crossplane (infrastructure from Kubernetes).
Example
hcl
# Terraform: create the VM
resource "aws_instance" "web" {
ami = "ami-0abc..."
instance_type = "t3.small"
}yaml
# Ansible: configure it
- hosts: web
become: true
tasks:
- ansible.builtin.apt: { name: nginx, state: present }
- ansible.builtin.service: { name: nginx, state: started, enabled: true }Common follow-ups
- Can Terraform configure servers? Through
user_data/cloud-init or provisioners, but provisioners are a last resort. Bake images or use a config tool. - Is Ansible idempotent? Its modules mostly are, but
shellandcommandtasks aren't unless you addcreatesorchanged_when.
What interviewers look for
Tip
"Provisioning vs configuration", declarative state vs procedural tasks, and where each fits in a modern container-based stack.
- Red flag: "they're the same thing, just pick one."