Skip to main content
15

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

TerraformAnsible
Main jobProvisioning (cloud APIs)Configuration management (OS level)
StyleDeclarative, with a planProcedural playbooks of mostly idempotent modules
StateState fileNone; checks the live system each run
LanguageHCLYAML
Typical targetsAWS/GCP/Azure, Kubernetes, SaaS APIsLinux/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 shell and command tasks aren't unless you add creates or changed_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."

Was this helpful?

Related questions