RDS PostgreSQL in Code
RDS and Aurora covered what RDS manages for you: backups, patching, Multi-AZ failover. In code, a production-ready PostgreSQL instance is not one resource but four: a DB subnet group (which private subnets it may live in), a security group (who may connect), a parameter group (PostgreSQL settings), and the instance itself. The database is also the resource where a careless plan does the most damage, so this lesson is as much about safety settings as about syntax.
The code
variable "environment" { type = string } # dev | prod
variable "vpc_id" { type = string }
variable "private_subnet_ids" { type = list(string) }
variable "app_security_group_id" { type = string }
locals {
is_prod = var.environment == "prod"
}
resource "aws_db_subnet_group" "this" {
name = "linkly-${var.environment}"
subnet_ids = var.private_subnet_ids # at least two zones
}
resource "aws_security_group" "db" {
name = "linkly-${var.environment}-db"
vpc_id = var.vpc_id
}
resource "aws_vpc_security_group_ingress_rule" "from_app" {
security_group_id = aws_security_group.db.id
referenced_security_group_id = var.app_security_group_id
ip_protocol = "tcp"
from_port = 5432
to_port = 5432
}
resource "aws_db_parameter_group" "this" {
name = "linkly-${var.environment}-pg17"
family = "postgres17"
parameter {
name = "log_min_duration_statement"
value = "500" # log queries slower than 500 ms
}
}
resource "aws_db_instance" "this" {
identifier = "linkly-${var.environment}"
engine = "postgres"
engine_version = "17"
instance_class = local.is_prod ? "db.m7g.large" : "db.t4g.micro"
allocated_storage = 20
max_allocated_storage = local.is_prod ? 200 : 50 # storage autoscaling
storage_type = "gp3"
storage_encrypted = true
db_name = "linkly"
username = "linkly_admin"
manage_master_user_password = true # AWS generates it and stores it in Secrets Manager
db_subnet_group_name = aws_db_subnet_group.this.name
vpc_security_group_ids = [aws_security_group.db.id]
parameter_group_name = aws_db_parameter_group.this.name
publicly_accessible = false
multi_az = local.is_prod
backup_retention_period = local.is_prod ? 14 : 1
deletion_protection = local.is_prod
skip_final_snapshot = !local.is_prod
final_snapshot_identifier = local.is_prod ? "linkly-${var.environment}-final" : null
auto_minor_version_upgrade = true
allow_major_version_upgrade = false
apply_immediately = !local.is_prod # prod changes wait for the maintenance window
}
output "endpoint" {
value = aws_db_instance.this.address
}
output "master_secret_arn" {
value = aws_db_instance.this.master_user_secret[0].secret_arn
}The safety settings, one by one:
| Setting | Why |
|---|---|
manage_master_user_password = true |
no password in your code, variables or state; the app reads it from Secrets Manager |
storage_encrypted = true |
can't be turned on later without a snapshot-and-restore |
publicly_accessible = false + private subnets |
the database has no public address |
deletion_protection (prod) |
AWS refuses deletes, even from destroy, until it's switched off in a reviewed change |
skip_final_snapshot = false (prod) |
a destroy still leaves a snapshot behind |
apply_immediately = false (prod) |
instance-class and parameter changes wait for the maintenance window instead of restarting now |
multi_az (prod) |
a standby in another zone for failover |
Add lifecycle { prevent_destroy = true } in prod as a second, CLI-side guard (Resources & Meta-Arguments).
dev vs prod, planned offline
The session plans the database module for both environments and prints the settings that differ, straight from the plan JSON:
mkdir -p db && cd db
cat > offline.tf <<'HCL'
provider "aws" {
region = "eu-west-1"
access_key = "offline"
secret_key = "offline"
skip_credentials_validation = true
skip_requesting_account_id = true
skip_metadata_api_check = true
}
HCL
cat > main.tf <<'HCL'
terraform {
required_providers {
aws = { source = "hashicorp/aws", version = "~> 6.0" }
}
}
variable "environment" {
type = string
validation {
condition = contains(["dev", "prod"], var.environment)
error_message = "dev or prod"
}
}
locals {
is_prod = var.environment == "prod"
}
resource "aws_db_subnet_group" "this" {
name = "linkly-${var.environment}"
subnet_ids = ["subnet-0aaa1111bbbb22223", "subnet-0ccc3333dddd44445"]
}
resource "aws_db_instance" "this" {
identifier = "linkly-${var.environment}"
engine = "postgres"
engine_version = "17"
instance_class = local.is_prod ? "db.m7g.large" : "db.t4g.micro"
allocated_storage = 20
max_allocated_storage = local.is_prod ? 200 : 50
storage_type = "gp3"
storage_encrypted = true
db_name = "linkly"
username = "linkly_admin"
manage_master_user_password = true
db_subnet_group_name = aws_db_subnet_group.this.name
publicly_accessible = false
multi_az = local.is_prod
backup_retention_period = local.is_prod ? 14 : 1
deletion_protection = local.is_prod
skip_final_snapshot = !local.is_prod
final_snapshot_identifier = local.is_prod ? "linkly-${var.environment}-final" : null
apply_immediately = !local.is_prod
}
HCL
tofu init >/dev/null
for env in dev prod; do
tofu plan -var environment=$env -out=$env.tfplan >/dev/null
done
for env in dev prod; do
tofu show -json $env.tfplan | jq -c --arg env "$env" '.resource_changes[] | select(.type == "aws_db_instance") | .change.after
| {env: $env, instance_class, multi_az, backup_retention_period, deletion_protection, skip_final_snapshot}'
done
echo "--- no password anywhere in the plan:"
tofu show -json prod.tfplan | jq '.resource_changes[] | select(.type == "aws_db_instance") | .change.after.password'{"env":"dev","instance_class":"db.t4g.micro","multi_az":false,"backup_retention_period":1,"deletion_protection":false,"skip_final_snapshot":true}
{"env":"prod","instance_class":"db.m7g.large","multi_az":true,"backup_retention_period":14,"deletion_protection":true,"skip_final_snapshot":false}
--- no password anywhere in the plan:
null
password is null: with a managed master password, the secret never passes through the CLI, so it can't leak from state or plan files.
Changes that replace the database
Some RDS arguments force a new instance, which means a new, empty database (or one restored from a snapshot if you arrange it): identifier (without identifier_prefix), engine, db_name, username, storage_encrypted, kms_key_id, availability_zone. A plan showing -/+ aws_db_instance must never be applied casually; the pipeline lessons show how to block such plans automatically. Changes that are safe in place: instance class, storage size (up only), backup settings, parameter group, multi_az, engine minor version.
A real apply takes a while; a sample:
$ tofu apply prod.tfplan
aws_db_subnet_group.this: Creating...
aws_db_subnet_group.this: Creation complete after 1s [id=linkly-prod]
aws_db_instance.this: Creating...
aws_db_instance.this: Still creating... [00m10s elapsed]
…
aws_db_instance.this: Still creating... [12m40s elapsed]
aws_db_instance.this: Creation complete after 12m47s [id=db-ABCDEFGHIJKLMNOPQRSTUVWXYZ]
Apply complete! Resources: 2 added, 0 changed, 0 destroyed.Test yourself
What does manage_master_user_password = true change?
- The password is stored in the state file encrypted
- AWS generates the master password and keeps it in Secrets Manager; it never appears in code, plan or state
- The password is printed in outputs
- It disables passwords
Which change to an existing aws_db_instance forces a replacement?
instance_classbackup_retention_periodstorage_encryptedfrom false to truemulti_az
Why set apply_immediately = false in production?
- It makes plans faster
- Disruptive modifications wait for the maintenance window instead of restarting the database now
- It disables backups
- It is required for Multi-AZ