Terraform IaC — Production Skill
Repository Structure
infrastructure/
├── modules/ # Reusable modules
│ ├── vpc/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ ├── outputs.tf
│ │ └── README.md
│ ├── ecs-service/
│ ├── rds-postgres/
│ └── cloudfront-s3/
├── environments/
│ ├── dev/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ ├── terraform.tfvars
│ │ └── backend.tf
│ ├── staging/
│ └── prod/
├── .terraform-version # Pin with tfenv
└── .github/workflows/terraform.yml
Backend Configuration (Remote State)
# environments/prod/backend.tf
terraform {
backend "s3" {
bucket = "mycompany-terraform-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
encrypt = true
kms_key_id = "alias/terraform-state"
dynamodb_table = "terraform-locks" # State locking
}
required_version = ">= 1.9.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.80"
}
}
}
# Bootstrap: create S3 bucket and DynamoDB table (once)
resource "aws_s3_bucket" "terraform_state" {
bucket = "mycompany-terraform-state"
lifecycle { prevent_destroy = true }
}
resource "aws_s3_bucket_versioning" "state" {
bucket = aws_s3_bucket.terraform_state.id
versioning_configuration { status = "Enabled" }
}
resource "aws_s3_bucket_server_side_encryption_configuration" "state" {
bucket = aws_s3_bucket.terraform_state.id
rule {
apply_server_side_encryption_by_default { sse_algorithm = "aws:kms" }
}
}
resource "aws_dynamodb_table" "terraform_locks" {
name = "terraform-locks"
billing_mode = "PAY_PER_REQUEST"
hash_key = "LockID"
attribute { name = "LockID"; type = "S" }
}
VPC Module
# modules/vpc/variables.tf
variable "name" { type = string }
variable "cidr" { type = string; default = "10.0.0.0/16" }
variable "azs" { type = list(string) }
variable "public_subnets" { type = list(string) }
variable "private_subnets" { type = list(string) }
variable "database_subnets" { type = list(string) }
variable "tags" { type = map(string); default = {} }
# modules/vpc/main.tf
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "~> 5.16"
name = var.name
cidr = var.cidr
azs = var.azs
public_subnets = var.public_subnets
private_subnets = var.private_subnets
database_subnets = var.database_subnets
enable_nat_gateway = true
single_nat_gateway = false # HA: one per AZ
enable_dns_hostnames = true
enable_dns_support = true
create_database_subnet_group = true
public_subnet_tags = {
"kubernetes.io/role/elb" = "1"
}
private_subnet_tags = {
"kubernetes.io/role/internal-elb" = "1"
}
tags = merge(var.tags, { Module = "vpc" })
}
# modules/vpc/outputs.tf
output "vpc_id" { value = module.vpc.vpc_id }
output "public_subnet_ids" { value = module.vpc.public_subnets }
output "private_subnet_ids" { value = module.vpc.private_subnets }
output "database_subnet_ids" { value = module.vpc.database_subnets }
output "database_subnet_group" { value = module.vpc.database_subnet_group_name }
RDS Module
# modules/rds-postgres/main.tf
resource "aws_db_instance" "this" {
identifier = var.identifier
engine = "postgres"
engine_version = "16.3"
instance_class = var.instance_class
db_name = var.db_name
username = var.username
password = random_password.db.result # Always random, store in Secrets Manager
allocated_storage = var.allocated_storage
max_allocated_storage = var.max_allocated_storage
storage_type = "gp3"
storage_encrypted = true
kms_key_id = aws_kms_key.rds.arn
multi_az = var.multi_az
db_subnet_group_name = var.db_subnet_group_name
vpc_security_group_ids = [aws_security_group.rds.id]
backup_retention_period = var.backup_retention_period
backup_window = "03:00-04:00"
maintenance_window = "Mon:04:00-Mon:05:00"
deletion_protection = var.deletion_protection
skip_final_snapshot = false
final_snapshot_identifier = "${var.identifier}-final-${formatdate("YYYY-MM-DD", timestamp())}"
performance_insights_enabled = true
performance_insights_retention_period = 7
monitoring_interval = 60
monitoring_role_arn = aws_iam_role.rds_monitoring.arn
parameter_group_name = aws_db_parameter_group.this.name
tags = var.tags
}
resource "aws_db_parameter_group" "this" {
family = "postgres16"
name = "${var.identifier}-params"
parameter {
name = "shared_preload_libraries"
value = "pg_stat_statements"
}
parameter {
name = "log_min_duration_statement"
value = "1000" # Log queries > 1 second
}
}
resource "random_password" "db" {
length = 32
special = false
}
resource "aws_secretsmanager_secret" "db_password" {
name = "${var.identifier}/password"
kms_key_id = aws_kms_key.secrets.arn
}
resource "aws_secretsmanager_secret_version" "db_password" {
secret_id = aws_secretsmanager_secret.db_password.id
secret_string = jsonencode({
username = var.username
password = random_password.db.result
host = aws_db_instance.this.address
port = aws_db_instance.this.port
dbname = var.db_name
})
}
ECS Service Module
# modules/ecs-service/main.tf
resource "aws_ecs_task_definition" "this" {
family = var.name
requires_compatibilities = ["FARGATE"]
network_mode = "awsvpc"
cpu = var.cpu
memory = var.memory
execution_role_arn = aws_iam_role.execution.arn
task_role_arn = aws_iam_role.task.arn
container_definitions = jsonencode([
{
name = var.name
image = var.container_image
portMappings = [{ containerPort = var.container_port }]
environment = [for k, v in var.environment_vars : { name = k, value = v }]
secrets = [for k, v in var.secrets : { name = k, valueFrom = v }]
logConfiguration = {
logDriver = "awslogs"
options = {
"awslogs-group" = aws_cloudwatch_log_group.this.name
"awslogs-region" = data.aws_region.current.name
"awslogs-stream-prefix" = "ecs"
}
}
healthCheck = {
command = ["CMD-SHELL", "curl -f http://localhost:${var.container_port}/health || exit 1"]
interval = 30
timeout = 5
retries = 3
startPeriod = 60
}
}
])
}
resource "aws_ecs_service" "this" {
name = var.name
cluster = var.cluster_id
task_definition = aws_ecs_task_definition.this.arn
desired_count = var.desired_count
launch_type = "FARGATE"
network_configuration {
subnets = var.private_subnet_ids
security_groups = [aws_security_group.service.id]
assign_public_ip = false
}
load_balancer {
target_group_arn = aws_lb_target_group.this.arn
container_name = var.name
container_port = var.container_port
}
deployment_circuit_breaker {
enable = true
rollback = true # Auto-rollback on deployment failure
}
lifecycle { ignore_changes = [desired_count] }
}
# Auto-scaling
resource "aws_appautoscaling_target" "ecs" {
service_namespace = "ecs"
resource_id = "service/${var.cluster_name}/${var.name}"
scalable_dimension = "ecs:service:DesiredCount"
min_capacity = var.min_capacity
max_capacity = var.max_capacity
}
resource "aws_appautoscaling_policy" "cpu" {
name = "${var.name}-cpu-scaling"
policy_type = "TargetTrackingScaling"
service_namespace = aws_appautoscaling_target.ecs.service_namespace
resource_id = aws_appautoscaling_target.ecs.resource_id
scalable_dimension = aws_appautoscaling_target.ecs.scalable_dimension
target_tracking_scaling_policy_configuration {
target_value = 70.0
predefined_metric_specification {
predefined_metric_type = "ECSServiceAverageCPUUtilization"
}
}
}
Environment Composition
# environments/prod/main.tf
locals {
name = "myapp"
environment = "prod"
region = "us-east-1"
tags = {
Project = local.name
Environment = local.environment
ManagedBy = "terraform"
}
}
provider "aws" {
region = local.region
default_tags { tags = local.tags }
}
module "vpc" {
source = "../../modules/vpc"
name = "${local.name}-${local.environment}"
azs = ["us-east-1a", "us-east-1b", "us-east-1c"]
public_subnets = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
private_subnets = ["10.0.11.0/24", "10.0.12.0/24", "10.0.13.0/24"]
database_subnets = ["10.0.21.0/24", "10.0.22.0/24", "10.0.23.0/24"]
tags = local.tags
}
module "rds" {
source = "../../modules/rds-postgres"
identifier = "${local.name}-${local.environment}"
instance_class = "db.r6g.xlarge"
multi_az = true
deletion_protection = true
backup_retention_period = 7
db_subnet_group_name = module.vpc.database_subnet_group
tags = local.tags
}
module "api" {
source = "../../modules/ecs-service"
name = "api"
cluster_id = aws_ecs_cluster.main.id
container_image = "${aws_ecr_repository.api.repository_url}:latest"
container_port = 8080
cpu = 1024
memory = 2048
desired_count = 2
min_capacity = 2
max_capacity = 20
private_subnet_ids = module.vpc.private_subnet_ids
tags = local.tags
}
GitHub Actions CI/CD
name: Terraform
on:
push:
branches: [main]
paths: ['infrastructure/**']
pull_request:
paths: ['infrastructure/**']
jobs:
terraform:
runs-on: ubuntu-latest
defaults:
run:
working-directory: infrastructure/environments/prod
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
with:
terraform_version: "1.9.8"
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::ACCOUNT:role/terraform-github
aws-region: us-east-1
- run: terraform init
- run: terraform fmt -check -recursive
- run: terraform validate
- run: terraform plan -out=tfplan
- name: Apply (main branch only)
if: github.ref == 'refs/heads/main'
run: terraform apply tfplan
Best Practices
# Always pin module and provider versions
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "~> 5.16" # Pessimistic constraint
}
# Use data sources instead of hardcoding IDs
data "aws_ami" "amazon_linux_2" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["amzn2-ami-hvm-*-x86_64-gp2"]
}
}
# Lifecycle rules to prevent accidental destruction
resource "aws_db_instance" "main" {
lifecycle {
prevent_destroy = true
ignore_changes = [engine_version] # Let AWS handle minor updates
}
}
# Use moved blocks for refactoring (avoid destroy/recreate)
moved {
from = aws_security_group.old_name
to = aws_security_group.new_name
}
# Variable validation
variable "environment" {
type = string
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "Environment must be dev, staging, or prod."
}
}
Useful Commands
terraform init -upgrade
terraform plan -target=module.rds
terraform apply -auto-approve
terraform state list
terraform state show aws_db_instance.main
terraform import aws_s3_bucket.legacy my-bucket
terraform output -json
terraform graph | dot -Tsvg > graph.svg