Automation

Terraform for RDS: Reusable Module Patterns and Drift Detection

How to build a safe, reusable Terraform module for Amazon RDS: sane defaults, deletion protection, secrets, parameter groups, testing and scheduled drift detection.

Databases are the one resource you cannot casually recreate. A good Terraform module makes the safe path the default path: encrypted, backed up, protected from deletion and consistent across environments. These are the patterns I reach for when building RDS modules.

1. Keep the interface small and opinionated

Expose what changes between teams (size, engine version, storage, environment) and hard-code the rest. Fewer variables mean fewer ways to misconfigure.

module "orders_db" {
  source         = "git::https://example.com/modules/rds-postgres.git?ref=v1.4.0"
  name           = "orders"
  environment    = "prod"
  instance_class = "db.r6g.xlarge"
  allocated_storage = 200
  engine_version = "15.5"
  multi_az       = true
  subnet_ids     = var.private_subnet_ids
  vpc_security_group_ids = [aws_security_group.db.id]
}

Always pin a module ref to a version tag so upgrades are deliberate.

2. Safe defaults inside the module

resource "aws_db_instance" "this" {
  identifier                = "${var.name}-${var.environment}"
  engine                    = "postgres"
  engine_version            = var.engine_version
  instance_class            = var.instance_class
  allocated_storage         = var.allocated_storage

  storage_encrypted         = true
  multi_az                  = var.multi_az
  backup_retention_period   = var.environment == "prod" ? 14 : 3
  deletion_protection       = var.environment == "prod"
  skip_final_snapshot       = false
  final_snapshot_identifier = "${var.name}-${var.environment}-final"
  performance_insights_enabled = true

  manage_master_user_password = true   # password stored in Secrets Manager

  db_subnet_group_name    = aws_db_subnet_group.this.name
  vpc_security_group_ids  = var.vpc_security_group_ids
  parameter_group_name    = aws_db_parameter_group.this.name

  lifecycle {
    prevent_destroy = true
  }
}

Check the attribute names against your AWS provider version, because arguments evolve. manage_master_user_password avoids passwords in state or code.

3. Manage parameter groups as code

Create a dedicated parameter group with the right family (for example postgres15) and set parameters explicitly. Note which parameters are static (need a reboot) and which are dynamic, and use apply_method = "pending-reboot" where required. Never rely on the default parameter group.

4. Be careful with apply_immediately

Changes such as instance class or engine version can cause downtime. Leave apply_immediately = false so they land in the maintenance window, and use a reviewed plan for anything that must happen now.

5. Test the module

  • terraform fmt -check and terraform validate on every PR.
  • tflint for provider-specific mistakes and a policy scanner (Checkov or tfsec) for security rules such as encryption and public access.
  • An integration test (for example Terratest) that creates a small instance in a sandbox account, connects and tears it down.

6. Detect drift on a schedule

terraform plan -detailed-exitcode returns 0 for no changes, 1 for errors and 2 when changes are pending, which is perfect for a nightly check:

name: drift-check
on:
  schedule: [{ cron: "0 3 * * *" }]
jobs:
  plan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: hashicorp/setup-terraform@v3
      - run: terraform init -input=false
      - run: terraform plan -detailed-exitcode -input=false
        # exit code 2 = drift or pending change: alert the team

Treat unexpected drift as an incident signal: someone changed production by hand.

7. Protect the state

Use a remote backend with locking and versioning (for example S3 with a lock mechanism), restrict who can read it, and keep one state per environment so a mistake in staging cannot touch production.

Checklist

  1. Small interface, version-pinned module.
  2. Encryption, backups, deletion protection on by default.
  3. Managed secrets, explicit parameter groups.
  4. Format, validate, lint and scan in CI.
  5. Nightly drift detection with alerts.

Enjoyed this?

I write about PostgreSQL, AWS and database reliability. Have a question or a similar problem to solve?