DevOps

Infrastructure as Code with Terraform on AWS

By Mohd Baquir Qureshi
Cloud Network

In the early days of cloud computing, engineers logged into the AWS console and manually clicked through forms to create EC2 instances, S3 buckets, and Security Groups. This process is unrepeatable, unversioned, and prone to human error. Infrastructure as Code (IaC) solves this.

Terraform, created by HashiCorp, is the industry standard tool for IaC. It allows you to declare exactly what your infrastructure should look like using a declarative language (HCL).

Defining a Basic AWS Environment

Let's look at a simple main.tf file that provisions a VPC, a public subnet, and a small EC2 instance running Ubuntu.

provider "aws" {
  region = "us-east-1"
}

# 1. Create a VPC
resource "aws_vpc" "main_vpc" {
  cidr_block = "10.0.0.0/16"
  enable_dns_hostnames = true
  
  tags = {
    Name = "Production-VPC"
  }
}

# 2. Create a Subnet within the VPC
resource "aws_subnet" "public_subnet" {
  vpc_id     = aws_vpc.main_vpc.id
  cidr_block = "10.0.1.0/24"
  map_public_ip_on_launch = true
}

# 3. Provision an EC2 Instance
resource "aws_instance" "web_server" {
  ami           = "ami-0c7217cdde317cfec" # Ubuntu 22.04 LTS
  instance_type = "t3.micro"
  subnet_id     = aws_subnet.public_subnet.id

  tags = {
    Name = "Web-Server-01"
  }
}

The Terraform Workflow

Terraform operates on a simple three-step workflow:

  1. terraform init: Initializes the directory, downloading the necessary provider plugins (like the AWS API client).
  2. terraform plan: Reads your code, checks the current state of AWS, and outputs a "diff" of exactly what it will create, modify, or destroy. This is a crucial safety check.
  3. terraform apply: Executes the plan, making API calls to AWS to provision the resources.

Understanding State Management

How does Terraform know that it already created the VPC when you run apply a second time? It relies on a State File (terraform.tfstate).

Critical Security Warning: By default, this file is stored locally on your hard drive. Because it contains the plain-text IDs of all your infrastructure (and potentially database passwords), you must never commit it to Git.

For team environments, you must configure a Remote Backend, storing the state file in an encrypted S3 bucket and using DynamoDB for state locking to prevent two engineers from running apply simultaneously.

terraform {
  backend "s3" {
    bucket         = "my-terraform-state-bucket"
    key            = "global/s3/terraform.tfstate"
    region         = "us-east-1"
    dynamodb_table = "terraform-locks"
    encrypt        = true
  }
}

Conclusion

Terraform elevates infrastructure to the same rigorous standards as application code. You can mandate code reviews for firewall changes, write automated tests for your network architecture, and theoretically re-provision your entire global cloud infrastructure from scratch in minutes if disaster strikes.