Table of Contents

Overview

Terraform and Ansible solve different problems. Terraform provisions infrastructure (creates VMs, networks, databases). Ansible configures what’s already running (installs packages, deploys apps, manages files). They’re complementary, not competing.

Declarative vs Procedural

Terraform is declarative — you describe the desired end state, and Terraform figures out how to get there.

resource "aws_instance" "web" {
  count         = 3
  ami           = "ami-abc123"
  instance_type = "t3.micro"
}

Ansible is procedural — you write step-by-step tasks that execute in order.

- name: Install nginx
  apt:
    name: nginx
    state: present
  become: true

Terraform is idempotent by design. Ansible tasks should be idempotent but it’s the author’s responsibility.

State Management

Terraform: Maintains a state file mapping config to real resources. Knows exactly what exists and what needs to change.

Ansible: Stateless — checks current state on each run. No state file to manage, but also no awareness of what it previously created.

Infrastructure vs Configuration

Terraform excels at:

  • Creating cloud resources (VMs, VPCs, databases, load balancers)
  • Managing resource lifecycle (create, update, destroy)
  • Dependency management between resources

Ansible excels at:

  • Installing and configuring software
  • Managing files, users, and services
  • Application deployment
  • Ad-hoc commands across fleets

Using Both Together

The most powerful approach: Terraform provisions, Ansible configures.

  1. Terraform creates EC2 instances, VPCs, security groups
  2. Terraform outputs instance IPs
  3. Ansible takes those IPs and configures the servers
# Terraform creates the server
resource "aws_instance" "web" {
  ami           = "ami-abc123"
  instance_type = "t3.micro"
}

# Output the IP for Ansible
output "web_ip" {
  value = aws_instance.web.public_ip
}

Then use Ansible with a dynamic inventory that reads from Terraform state or cloud provider APIs.

When to Use Each

Use Terraform when:

  • Creating or destroying cloud infrastructure
  • Managing resource dependencies
  • Working with cloud provider APIs
  • You need a clear picture of what exists (state)

Use Ansible when:

  • Configuring servers after creation
  • Deploying applications
  • Running ad-hoc tasks across servers
  • Managing on-premises infrastructure

Use both when: You need full-stack automation from infrastructure creation to application deployment.

Hands-On Courses

Learn by doing with interactive courses on CopyPasteLearn:

Conclusion

Terraform and Ansible are better together than apart. Terraform handles the ‘what infrastructure exists’ question; Ansible handles the ‘how is it configured’ question. Master both for complete infrastructure automation.