Terraform lets you define your entire AWS infrastructure as code — version-controlled, reviewable, and reproducible. This guide walks you through building a production-grade AWS environment from scratch.
Provider Configuration
terraform {
required_version = ">= 1.6"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
backend "s3" {
bucket = "my-terraform-state"
key = "production/terraform.tfstate"
region = "eu-central-1"
encrypt = true
dynamodb_table = "terraform-locks"
}
}
provider "aws" {
region = var.region
}
VPC with Public/Private Subnets
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
enable_dns_hostnames = true
tags = { Name = "${var.env}-vpc" }
}
resource "aws_subnet" "public" {
count = 2
vpc_id = aws_vpc.main.id
cidr_block = "10.0.${count.index + 1}.0/24"
availability_zone = data.aws_availability_zones.available.names[count.index]
map_public_ip_on_launch = true
tags = { Name = "${var.env}-public-${count.index + 1}" }
}
resource "aws_subnet" "private" {
count = 2
vpc_id = aws_vpc.main.id
cidr_block = "10.0.${count.index + 10}.0/24"
availability_zone = data.aws_availability_zones.available.names[count.index]
tags = { Name = "${var.env}-private-${count.index + 1}" }
}
Application Load Balancer
resource "aws_lb" "app" {
name = "${var.env}-alb"
internal = false
load_balancer_type = "application"
security_groups = [aws_security_group.alb.id]
subnets = aws_subnet.public[*].id
}
resource "aws_lb_target_group" "app" {
name = "${var.env}-tg"
port = 80
protocol = "HTTP"
vpc_id = aws_vpc.main.id
health_check {
path = "/health"
healthy_threshold = 2
unhealthy_threshold = 10
}
}
RDS Database
resource "aws_db_instance" "main" {
identifier = "${var.env}-postgres"
engine = "postgres"
engine_version = "16.1"
instance_class = "db.t3.medium"
allocated_storage = 100
storage_encrypted = true
multi_az = var.env == "production"
db_name = "myapp"
username = "admin"
password = var.db_password
db_subnet_group_name = aws_db_subnet_group.main.name
vpc_security_group_ids = [aws_security_group.db.id]
skip_final_snapshot = false
backup_retention_period = 7
}
📘 Master Infrastructure as Code
Our Terraform and AWS eBooks cover everything from basics to multi-account architectures with CI/CD pipelines.
Browse DevOps Books →Terraform transforms cloud infrastructure from manual ClickOps into version-controlled, reproducible code. Start with a VPC module, add your compute and database resources, and you'll have infrastructure that can be reviewed in PRs just like application code.