Lesson 6 of 6 · Infrastructure as Code with Terraform

Terraform for Databases

Protecting databases from destruction, spotting replacements, keeping secrets out, what Terraform should manage, and running it through a pipeline.

Beginner 8 sections 4 min read

Databases need extra care

Terraform treats most infrastructure as replaceable: if something's wrong, destroy it and build a new one. A database can't be treated that way, because it holds data that code can't recreate. These practices let DBAs get Terraform's benefits while making sure it can never casually delete or rebuild a database.

Protect databases from destruction

Use two layers of protection, one in Terraform and one in the cloud itself:

# AWS: an RDS database protected twice
resource "aws_db_instance" "sales" {
  identifier                  = "sales-prod"
  engine                      = "oracle-se2"
  license_model               = "license-included"
  instance_class              = "db.m6i.large"
  allocated_storage           = 200
  storage_type                = "gp3"
  multi_az                    = true
  storage_encrypted           = true
  manage_master_user_password = true    # password kept in Secrets Manager
  username                    = "admin"
  backup_retention_period     = 14

  deletion_protection       = true      # the cloud refuses to delete it
  skip_final_snapshot       = false     # take a snapshot if it's ever deleted
  final_snapshot_identifier = "sales-prod-final"

  lifecycle {
    prevent_destroy = true              # Terraform refuses any plan that would destroy it
  }
}
lifecycle prevent_destroy
Terraform stops with an error if any plan would destroy this resource, including a replacement. Removing the protection takes a deliberate, reviewed code change.
Cloud deletion protection
Settings such as deletion_protection on RDS, or locks on Azure resources, make the cloud itself refuse the delete, whoever asks.
Final snapshots
If a database is ever deleted, a last backup is taken first.

Watch for replacements

Some arguments can't be changed on an existing database: changing them makes Terraform destroy the database and create a new one. Which arguments these are depends on the resource, such as the database name, engine, or certain storage settings. The plan always says so:

  # aws_db_instance.sales must be replaced
-/+ resource "aws_db_instance" "sales" {
      ~ identifier = "sales-prod" -> "sales-production" # forces replacement

A -/+ on a database in a plan is a stop sign. With prevent_destroy set, Terraform refuses it outright; without it, applying would delete the data. Check each resource's documentation for which arguments force replacement, and plan those changes as proper database migrations instead.

Keep secrets out of code

  • Let the cloud manage the password where it can, such as RDS's manage_master_user_password, which stores it in AWS Secrets Manager.
  • Read secrets from a vault at run time, with a data source for OCI Vault, AWS Secrets Manager, Azure Key Vault, or HashiCorp Vault.
  • Pass secrets as environment variables in pipelines, such as TF_VAR_admin_password, set from the pipeline's secret store, rather than in .tfvars files.
  • Mark variables sensitive = true so they're hidden in plan and apply output, and remember state still holds them: protect the state.

What Terraform should and shouldn't manage

Good fit for TerraformBetter elsewhere
Database servers, managed databases, and clustersTables, indexes, and other schema objects: Liquibase or Flyway
Parameter groups, sizes, storage, backup and HA settingsThe data itself: backups, Data Pump, replication
Networks, security groups, private endpoints, keysSoftware and settings inside a server: Ansible
Monitoring alarms and dashboards for the databaseDay-to-day users and grants: migrations or Ansible

Hand results to the next tool through outputs. For example, Terraform outputs a new server's IP address, and the pipeline passes it to Ansible as its inventory, as in Git in Practice.

Running Terraform through a pipeline

For anything beyond experiments, Terraform runs from a pipeline, not from laptops, so every change is reviewed, planned, approved, and logged in the same way:

Pull requestChecksReviewApply to dev Apply to prod code changeon a branch fmt, validate,plan posted code and plan:any -/+ or - ? after merge,automatically after anapproval Nightly drift check plan -refresh-only, alert on changes

Pipeline credentials should allow only what Terraform needs, and production credentials should be available only to the production stage. Tools such as Atlantis and HCP Terraform, from the GitOps lesson, run this workflow for you.

Best practices summary

  • Pin Terraform and provider versions, and commit .terraform.lock.hcl.
  • Keep state remote, locked, encrypted, versioned, and separate per environment.
  • Use modules for standard designs, and separate folders and credentials for production.
  • Protect databases with prevent_destroy, cloud deletion protection, and final snapshots.
  • Read every plan; treat replacements and destroys of databases as stop signs.
  • Keep secrets in vaults and out of code, logs, and Git.
  • Tag everything for ownership and cost.
  • Run Terraform from a pipeline, with review, approval, and drift checks.
  • Never change Terraform-managed resources by hand; if you must in an emergency, update the code straight after.

Key takeaways

  • Databases hold data that code can't recreate, so they need protection from destroys and replacements.
  • Use prevent_destroy, cloud deletion protection, and final snapshots together.
  • Some argument changes force replacement; plan them as migrations instead.
  • Keep secrets in vaults or cloud-managed passwords, and protect state, which can contain them.
  • Terraform manages the database's infrastructure; schema, data, and in-server settings belong to other tools.
  • Run Terraform through a pipeline: plan on pull requests, review, apply with approval, and check for drift nightly.