Terraform for Databases
Protecting databases from destruction, spotting replacements, keeping secrets out, what Terraform should manage, and running it through a pipeline.
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_protectionon 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.tfvarsfiles. - Mark variables
sensitive = trueso 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 Terraform | Better elsewhere |
|---|---|
| Database servers, managed databases, and clusters | Tables, indexes, and other schema objects: Liquibase or Flyway |
| Parameter groups, sizes, storage, backup and HA settings | The data itself: backups, Data Pump, replication |
| Networks, security groups, private endpoints, keys | Software and settings inside a server: Ansible |
| Monitoring alarms and dashboards for the database | Day-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:
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.