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
| Feature | Multi-AZ | Read Replica |
|---|---|---|
| Purpose | High availability / failover | Read scaling |
| Standby visible | No, automatic failover only | Yes, separate endpoint |
| Automatic failover | Yes | No |
| Cost | 2x | 2x |
| Cross-region | No | Yes |
# 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
- What does
multi_az = trueprovide? - What is
max_allocated_storageused for? - Why would you set
ignore_changes = [password]? - What is the difference between
skip_final_snapshotanddeletion_protection? - When would you use a read replica instead of Multi-AZ?