I codified a hardened cloud database baseline in Terraform with private-subnet networking, KMS encryption at rest, and automated backups. Infrastructure-as-code made the secure configuration repeatable, reviewable, and drift-detectable across environments.

Objective & Context

Cloud database security is a configuration problem solved best as code. This lab provisions a managed database (AWS RDS / Azure SQL) into a private subnet with no public endpoint, enables encryption with a customer-managed key, and sets a backup retention window, aligning to CIS cloud benchmarks.

Environment & Prerequisites

  • Terraform 1.7 with a cloud provider configured.
  • An existing VPC/VNet with private subnets.
  • A KMS/Key Vault key for encryption.

Step-by-Step Execution

1. Declare a private, encrypted database

resource "aws_db_instance" "app" {
  engine                  = "postgres"
  instance_class          = "db.t3.medium"
  storage_encrypted       = true
  kms_key_id              = aws_kms_key.db.arn
  publicly_accessible     = false
  backup_retention_period = 14
  db_subnet_group_name    = aws_db_subnet_group.private.name
}

2. Plan and apply

terraform plan -out tf.plan && terraform apply tf.plan

3. Detect drift later

terraform plan -detailed-exitcode
aws_db_instance.app: Creation complete (encrypted, private)
No changes. Infrastructure matches configuration.

Validation & Testing

Confirm the database has no public endpoint, storage is encrypted with the CMK, and backups are retained. Pass criteria: connection only succeeds from inside the VPC, encryption is enabled, and terraform plan reports no drift after apply.

Advanced: Troubleshooting
  • Public exposure: set publicly_accessible=false and place in private subnets only.
  • Encryption can't be added later: enable at creation; retrofitting often requires a re-create.
  • State drift: remediate via Terraform, not console edits, to keep code authoritative.

Key Results

  • Codified a private, encrypted database baseline as reusable Terraform.
  • Eliminated public database endpoints across environments.
  • Enabled KMS encryption at rest and 14-day backup retention.
  • Gained drift detection via terraform plan.