Part 4 ยท Chapter 12

Terraform: LEGO Instructions for Servers

Write code once, build infrastructure anywhere โ€” repeatably and reliably.

What you'll learn in this chapter

  • What Infrastructure as Code (IaC) is and why it solved one of DevOps's biggest headaches
  • Terraform's core concepts: providers, resources, variables, outputs, state, and modules
  • How to write a complete Terraform configuration that builds real AWS infrastructure
  • The three-command Terraform workflow: init, plan, apply
  • Why Terraform state is sacred and how to manage it safely with remote backends
  • How to build reusable infrastructure with Terraform modules
  • OpenTofu โ€” the open-source Terraform fork and why it exists

The LEGO Instructions Analogy

Imagine you spent a weekend building an incredible LEGO castle โ€” towers, a drawbridge, a throne room, the whole thing. Your friend sees it and says: "I want the exact same castle for my desk." You could sit down with them and describe it verbally. "OK, first you put three 2x4 bricks here, then a 1x2 on top, then..." But no matter how carefully you describe it, they'll build something slightly different. A tower ends up a block taller. The drawbridge faces the wrong way. It's close, but not the same.

The other option: you write precise, numbered LEGO instructions with pictures. Now anyone, anywhere, at any time, can build the exact same castle perfectly. You could build it again yourself after taking it apart. You could build ten castles simultaneously. The instructions are the source of truth.

Terraform is that instruction manual โ€” but for cloud infrastructure instead of LEGO bricks.

๐Ÿฐ The Problem Terraform Solves

Before Infrastructure as Code (IaC), setting up servers meant clicking around in the AWS console โ€” manually creating VPCs, subnets, EC2 instances, security groups, load balancers, one by one. Engineers would spend hours clicking through menus. If you needed to recreate the environment for staging, or for disaster recovery, or for a new region, you'd have to click everything again โ€” from memory. And if you misremembered one setting, your staging environment would be subtly different from production. Bugs would hide in those differences.

Terraform lets you write your entire infrastructure as code โ€” plain text files that precisely describe every server, network, database, and load balancer you need. Run terraform apply and it builds everything, identically, every time. Your infrastructure is now version-controlled, reviewable in pull requests, and perfectly reproducible.

The Terraform Workflow โ€” Three Commands to Rule Them All

Terraform's daily workflow is remarkably simple. Think of it like a pilot's pre-flight checklist: prepare, review, confirm. Three stages, in order, every time.

The Core Terraform Loop

Write .tf files  โ†’  terraform init (download plugins)  โ†’  terraform plan (preview changes)  โ†’  terraform apply (make it real)  โ†’  terraform destroy (tear it down)
  • terraform init โ€” Downloads providers and modules. Like npm install before running a Node project. Must run this first in any new project directory.
  • terraform plan โ€” Shows exactly what Terraform would create, change, or destroy โ€” without actually doing anything. This is your safety net. Read the plan before every apply.
  • terraform apply โ€” Executes the changes. Terraform shows you the plan one more time and asks for confirmation before touching anything.
  • terraform destroy โ€” Tears down all infrastructure managed by Terraform in the current configuration. Use with care.
๐Ÿ’ก Always Plan Before Apply

The plan command is your best friend. It shows you the exact diff of what will change: green + for creates, yellow ~ for updates, red - for destroys. Make it a habit to always read the plan output carefully before typing yes on apply. Many production incidents have been caused by someone applying without reading the plan.

Terraform Core Concepts

Terraform has a small vocabulary. Learn these seven terms and you understand 90% of how Terraform works.

๐Ÿ“– Key Terms
  • Provider: the plugin that talks to a specific platform (AWS, GCP, Azure, Cloudflare, GitHub, Datadog...). Like a driver for your specific car โ€” Terraform's engine is the same, but the provider is what speaks AWS's language.
  • Resource: a single piece of infrastructure that Terraform manages. An EC2 instance, an S3 bucket, a DNS record, a database โ€” each is a resource block in your code.
  • Data Source: a way to look up existing infrastructure that Terraform didn't create. "Find me the ID of the latest Ubuntu AMI" โ€” that's a data source.
  • Variable: an input parameter that makes your config reusable. Instead of hardcoding "us-east-1" in fifty places, define a variable and reference it everywhere.
  • Output: a value that Terraform exports after apply. "Here is the IP address of the server I just created." Outputs are how stacks communicate with each other.
  • State: Terraform's memory. It remembers every resource it ever created in a file called terraform.tfstate. Without state, Terraform doesn't know what already exists.
  • Module: a reusable group of resources packaged as a directory. Like a function in programming โ€” call it with inputs, get infrastructure out.

Your First Terraform Configuration

Let's build something real. The following configuration creates a complete AWS environment: a VPC (private network), a public subnet, an internet gateway, a security group, and an EC2 instance running Nginx. This is a real, working setup you can deploy.

Terraform configurations live in files ending in .tf. By convention, teams split configs across multiple files: provider.tf for provider setup, variables.tf for inputs, main.tf for resources, and outputs.tf for exports.

provider.tf โ€” Setting Up the AWS Connection

# provider.tf
terraform {
  required_version = ">= 1.5"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }

  # Store state in S3 โ€” essential for teams
  backend "s3" {
    bucket = "my-terraform-state-bucket"
    key    = "production/terraform.tfstate"
    region = "us-east-1"
  }
}

provider "aws" {
  region = var.aws_region
}

variables.tf โ€” Input Parameters

# variables.tf
variable "aws_region" {
  description = "AWS region to deploy into"
  type        = string
  default     = "us-east-1"
}

variable "environment" {
  description = "Environment name (production, staging)"
  type        = string
}

variable "instance_type" {
  description = "EC2 instance type"
  type        = string
  default     = "t3.micro"
}

main.tf โ€” The Infrastructure Resources

# main.tf

# VPC โ€” our private network in AWS
resource "aws_vpc" "main" {
  cidr_block           = "10.0.0.0/16"
  enable_dns_hostnames = true

  tags = {
    Name        = "${var.environment}-vpc"
    Environment = var.environment
  }
}

# Public subnet โ€” where our web server lives
resource "aws_subnet" "public" {
  vpc_id                  = aws_vpc.main.id
  cidr_block              = "10.0.1.0/24"
  availability_zone       = "${var.aws_region}a"
  map_public_ip_on_launch = true

  tags = {
    Name = "${var.environment}-public-subnet"
  }
}

# Internet Gateway โ€” the door to the outside world
resource "aws_internet_gateway" "main" {
  vpc_id = aws_vpc.main.id
  tags   = { Name = "${var.environment}-igw" }
}

# Security Group โ€” allow HTTP, HTTPS, and SSH
resource "aws_security_group" "web" {
  name   = "${var.environment}-web-sg"
  vpc_id = aws_vpc.main.id

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["YOUR_IP/32"]  # Always restrict SSH to your IP
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

# EC2 Instance โ€” the web server itself
resource "aws_instance" "web" {
  ami                    = data.aws_ami.ubuntu.id
  instance_type          = var.instance_type
  subnet_id              = aws_subnet.public.id
  vpc_security_group_ids = [aws_security_group.web.id]
  key_name               = "my-key-pair"

  user_data = <<-EOF
    #!/bin/bash
    apt-get update
    apt-get install -y nginx
    systemctl enable nginx
    systemctl start nginx
  EOF

  tags = {
    Name        = "${var.environment}-web-server"
    Environment = var.environment
  }
}

# Data source: look up the latest Ubuntu 22.04 AMI
data "aws_ami" "ubuntu" {
  most_recent = true
  owners      = ["099720109477"]  # Canonical's AWS account ID

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"]
  }
}

outputs.tf โ€” Export Useful Values

# outputs.tf
output "web_server_ip" {
  description = "Public IP of the web server"
  value       = aws_instance.web.public_ip
}

output "vpc_id" {
  description = "ID of the created VPC"
  value       = aws_vpc.main.id
}

Deploying the Configuration

# Step 1: Initialize (download the AWS provider plugin)
terraform init

# Step 2: Preview what will be created
terraform plan -var="environment=staging"

# Step 3: Apply using a variables file
terraform apply -var-file="staging.tfvars"

# Show the current state of infrastructure
terraform show

# List all resources Terraform is tracking
terraform state list

# Tear everything down (prompts for confirmation)
terraform destroy
๐Ÿคฏ Fun Fact: How Fast Is Terraform?

A well-written Terraform configuration can spin up a complete production environment โ€” VPC, subnets, security groups, load balancer, multiple EC2 instances, RDS database, and S3 buckets โ€” in under five minutes. What used to take a senior engineer an entire day of clicking through AWS console is now five minutes of automated, reproducible, version-controlled work.

Terraform State โ€” The Sacred Memory

Here's something that trips up every Terraform beginner: Terraform doesn't just look at your .tf files and compare them to live AWS. It also keeps a state file (terraform.tfstate) that records every resource it has ever created โ€” the resource IDs, IP addresses, configuration โ€” everything.

Think of it like a landlord's ledger. The landlord (Terraform) keeps detailed records of every apartment they manage. When you ask for changes, they check their ledger first: "I already created that VPC โ€” its ID is vpc-0abc123. I'll update it rather than create a new one." Without the ledger, the landlord would try to create a brand new apartment in an already-occupied building โ€” chaos.

The State File Flow

Your .tf files (desired state)  +  terraform.tfstate (current state)  โ†’  Terraform computes the diff  โ†’  Applies only what's necessary
โš ๏ธ The Three Rules of Terraform State
  1. Never edit terraform.tfstate manually. The file has a precise format and internal checksums. Manual edits corrupt it. Use terraform state commands if you need to manipulate state.
  2. Never delete the state file. If you delete it, Terraform loses track of what it created. Your next apply will try to create everything again, causing resource conflicts and duplicate infrastructure.
  3. Never commit state to Git. State files contain sensitive values โ€” database passwords, private keys, API tokens โ€” in plain text. Store state in a remote backend like AWS S3 with DynamoDB for locking.

Remote State with S3 and DynamoDB

For any team project (more than one person), you must store state remotely so everyone shares the same truth. AWS S3 stores the file; DynamoDB provides locking so two engineers can't apply at the same time and corrupt the state.

# First, create the S3 bucket and DynamoDB table (once, manually or via a bootstrap config)

# Then reference the backend in your config:
backend "s3" {
  bucket         = "my-company-terraform-state"
  key            = "production/terraform.tfstate"
  region         = "us-east-1"
  encrypt        = true
  dynamodb_table = "terraform-state-lock"  # Prevents concurrent applies
}

Terraform Modules โ€” Reusable Infrastructure Blueprints

Once you've written Terraform code for a VPC, why write it again for your staging environment? And again for your QA environment? Modules let you package infrastructure as a reusable component โ€” like a function in programming. Call the module with different inputs; get consistent infrastructure out.

Here's how you call a module you've written locally or downloaded from the Terraform Registry:

# Use a local module
module "web_server" {
  source        = "./modules/ec2-web-server"
  environment   = "production"
  instance_type = "t3.medium"
  vpc_id        = module.vpc.id
}

# Use a community module from the Terraform Registry
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "5.0.0"

  name = "${var.environment}-vpc"
  cidr = "10.0.0.0/16"

  azs             = ["us-east-1a", "us-east-1b", "us-east-1c"]
  private_subnets = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
  public_subnets  = ["10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24"]

  enable_nat_gateway = true
}
๐Ÿ’ก The Terraform Registry

Visit registry.terraform.io โ€” it's full of battle-tested community modules for common patterns: AWS VPC, EKS cluster, RDS PostgreSQL, S3 website, and hundreds more. Instead of writing 200 lines of VPC Terraform code from scratch, you can use a well-tested module with 10 lines of configuration. Check download counts and GitHub stars to identify quality modules.

Terraform Workspaces โ€” One Config, Multiple Environments

Workspaces let you manage multiple environments (staging, production, QA) from a single Terraform configuration. Each workspace has its own state file, so staging and production don't interfere with each other. Think of workspaces like Git branches โ€” same code, different state.

# Create and switch to a staging workspace
terraform workspace new staging
terraform workspace select staging

# List all workspaces (* marks current)
terraform workspace list
#   default
# * staging
#   production

# In your .tf files, reference the workspace name
resource "aws_instance" "web" {
  instance_type = terraform.workspace == "production" ? "t3.medium" : "t3.micro"
}

OpenTofu โ€” The Open Source Fork

In August 2023, HashiCorp (the company that created Terraform) changed Terraform's license from the Mozilla Public License (fully open source) to the Business Source License (BSL). The BSL restricts commercial use โ€” specifically, you cannot build competing products that substantially use Terraform. This change concerned the open source community significantly.

The community responded by forking the last open-source version of Terraform into a new project called OpenTofu, now managed by the Linux Foundation. OpenTofu is 100% syntactically compatible with Terraform โ€” the same HCL syntax, the same provider ecosystem, the same commands. You can switch from Terraform to OpenTofu by simply replacing the binary.

๐Ÿ“– OpenTofu vs Terraform
  • OpenTofu: truly open source (MPL 2.0 license), managed by the Linux Foundation, community-driven, 100% compatible with Terraform syntax and providers
  • Terraform: BSL license (restricts competing commercial use), managed by HashiCorp (now IBM), the most widely-used and has a larger existing ecosystem
  • When to use OpenTofu: open-source projects, organizations concerned about licensing, when building tooling that extends Terraform's functionality
  • When to use Terraform: established teams already using it, when Terraform-specific enterprise features (Terraform Cloud, HCP Terraform) are valuable
# Install OpenTofu (drop-in replacement for Terraform)
brew install opentofu           # macOS
winget install OpenTofu.OpenTofu # Windows

# All commands are identical โ€” just replace "terraform" with "tofu"
tofu init
tofu plan
tofu apply

Terraform in a CI/CD Pipeline

In a mature team, engineers don't run terraform apply from their laptops. Instead, Terraform runs inside a CI/CD pipeline. A pull request gets opened with infrastructure changes, the pipeline runs terraform plan and posts the output as a PR comment, a senior engineer reviews the plan, merges the PR, and the pipeline automatically applies. This is the GitOps model applied to infrastructure.

# Example GitHub Actions workflow for Terraform
name: Terraform Plan and Apply

on:
  pull_request:
    branches: [main]

jobs:
  terraform:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Setup Terraform
        uses: hashicorp/setup-terraform@v3

      - name: Terraform Init
        run: terraform init

      - name: Terraform Plan
        run: terraform plan -no-color -out=plan.tfplan

      - name: Post Plan to PR
        uses: actions/github-script@v7
        # Posts the plan output as a comment on the pull request

Chapter Summary

  • Terraform is Infrastructure as Code โ€” write text files that describe your infrastructure, and Terraform builds it identically every time.
  • The core workflow is three steps: init (download plugins), plan (preview changes), apply (execute).
  • The seven core concepts are: Provider, Resource, Data Source, Variable, Output, State, and Module.
  • Terraform state (terraform.tfstate) is Terraform's memory. Store it remotely in S3, never in Git, never edit it manually.
  • Modules are reusable infrastructure components. The Terraform Registry offers thousands of battle-tested modules for common patterns.
  • Workspaces let you manage multiple environments (staging, production) from a single configuration with separate state files.
  • OpenTofu is a 100% compatible open-source fork of Terraform, managed by the Linux Foundation, created in response to HashiCorp's license change.