Skip to main content

Module 13, AWS Databases with Terraform

RDS PostgreSQL

resource "aws_db_instance" "main" {
identifier = "${var.app_name}-postgres"
engine = "postgres"
engine_version = "15.18"
instance_class = var.db_instance_class

allocated_storage = 20
max_allocated_storage = 100 # enables autoscaling up to 100 GB
storage_type = "gp3"
storage_encrypted = true

db_name = var.db_name
username = var.db_username
password = var.db_password

multi_az = var.environment == "production"
db_subnet_group_name = aws_db_subnet_group.main.name
vpc_security_group_ids = [aws_security_group.rds.id]
publicly_accessible = false

backup_retention_period = 7
deletion_protection = var.environment == "production"
skip_final_snapshot = var.environment != "production"

lifecycle {
ignore_changes = [password] # managed by Secrets Manager rotation
}
}

resource "aws_db_subnet_group" "main" {
name = "${var.app_name}-db-subnet-group"
subnet_ids = aws_subnet.private_data[*].id
}

Multi-AZ vs Read Replicas

FeatureMulti-AZRead Replica
PurposeHigh availability / failoverRead scaling
Standby visibleNo, automatic failover onlyYes, separate endpoint
Automatic failoverYesNo
Cost2x2x
Cross-regionNoYes
# Read replica
resource "aws_db_instance" "read_replica" {
identifier = "${var.app_name}-postgres-replica"
replicate_source_db = aws_db_instance.main.identifier
instance_class = "db.t3.micro"
publicly_accessible = false
skip_final_snapshot = true
}

DynamoDB

resource "aws_dynamodb_table" "sessions" {
name = "${var.app_name}-sessions"
billing_mode = "PAY_PER_REQUEST"
hash_key = "userId"
range_key = "sessionId"

attribute { name = "userId"; type = "S" }
attribute { name = "sessionId"; type = "S" }

ttl {
attribute_name = "expiresAt"
enabled = true
}

tags = local.common_tags
}

Knowledge Check

  1. What does multi_az = true provide?
  2. What is max_allocated_storage used for?
  3. Why would you set ignore_changes = [password]?
  4. What is the difference between skip_final_snapshot and deletion_protection?
  5. When would you use a read replica instead of Multi-AZ?