// Why this matters
A managed database fleet built from Terraform modules turns a recurring, risky chore into a reviewed pull request. Every team needs PostgreSQL, a cache and sometimes MongoDB or a managed streaming service, and if each one is hand-clicked the result is a zoo: public IPs on some, no backups on others, and passwords in chat history.
Modules make the safe path the easy path. They also mean a security or backup improvement is made once and rolled out to every instance on the next apply, which is how a small platform team keeps dozens of databases consistent.
// The problem
Databases are where infrastructure mistakes become incidents. A publicly reachable instance with a weak password is a breach. An instance without deletion protection can vanish with one wrong terraform destroy. Backups that exist but were never restored fail at the worst moment.
Multiple providers add friction. Cloud-native services, a third-party document database and a managed data platform each have different networking models: peering, private endpoints and VPC peering to a vendor-hosted network. Without a pattern, every project reinvents the wiring.
// The solution
The modules share a shape. Inputs are name, tier or size, network, labels and a handful of toggles; outputs are connection metadata such as a private address and secret reference, never the password itself. Defaults are the safe choice: private IP only, backups enabled, deletion protection enabled, maintenance window set and flags that harden the engine.
For Cloud SQL PostgreSQL the network is prepared once with a reserved private service access range and a peering to the producer network. Each instance then gets a private IP in that range. For Memorystore Redis the module uses private service access or direct peering with transit encryption and authentication turned on.
For MongoDB the module creates the cluster and a private endpoint service connection to the application network, so traffic never crosses the public internet; the allowlist stays empty. For Aiven services (PostgreSQL, Kafka, others) the module creates the service in a project and sets up VPC peering to the customer network with an allowed IP range for CIDR safety.
Credentials follow one rule: Terraform generates a random value, writes it to the secret manager and exposes only the secret's name. Backups combine the managed daily backup with scheduled exports to object storage for the stores where point-in-time recovery is limited, plus a scratch-restore drill. I rejected building one generic mega-module covering every engine because the inputs diverge too much; related but separate modules read better. The same principle of small reusable modules underpins The GCP Project Factory: Folder, Project, VPC and GKE per Tenant and Subscription Factory: Customer Onboarding That Starts by Minting Subscriptions.
- Networkprivate service access range and peering reserved once
- Module callteam picks type, size, name
- Create instanceprivate IP, flags, maintenance window
- Gate: deletion protection gatedestroy blocked unless explicitly lifted
- Generate credentialsrandom password written to secret manager
- Private connectivitypeering or endpoint service to the app network
- Backupsmanaged backups plus scheduled exports
- Monitoralerts on storage, connections, replication lag
- Restore drillperiodic restore into a scratch instance
- Reserve networkprivate range and peering once per VPC
- Create moduleteam passes name and size
- Credentialsgenerate and store in secret manager
- Review gateplan reviewed in a pull request
- Applypipeline creates the instance
- Backupmanaged plus scheduled export
- Restore drillrestore to scratch and verify rows
// Before you start
- Terraform 1.6 or newer and provider credentials supplied through your pipeline (not committed)
- A VPC in the target cloud and permission to create private service access ranges and peerings
- Provider accounts for MongoDB Atlas and Aiven, with API credentials stored in a secret manager
- A secret manager for credentials and a bucket for exports
- Knowledge of your engines' backup and restore tools (pg_dump or managed export, mongodump)
// Step-by-step implementation
01 Step 1. Reserve private service access once per network
Cloud SQL private IPs come from a range you reserve and peer with the service producer network. Do it once per VPC, not per database, and pick a range that does not overlap anything else you route.
02 Step 2. Write the PostgreSQL module with safe defaults
The module takes few inputs and fixes the rest. Note the private-only IP configuration, backups with point-in-time recovery, deletion protection and flags that log slow queries and enforce TLS.
03 Step 3. Store the credential and expose only a reference
Write the generated password into the secret manager and output only the secret id and private address. Consumers read the secret at runtime through workload identity. Marking any output sensitive is not enough; do not output it at all.
04 Step 4. Add a Redis module with auth and encryption
A cache is still a database. Enable authentication and in-transit encryption and keep it on a private network. Choose standard tier for replication where the cache loss would hurt.
05 Step 5. MongoDB with a private endpoint and no public allowlist
Create the cluster with the Atlas provider and connect it to your network through a private endpoint, so applications resolve a private hostname. Leave the IP access list empty rather than opening zero-zero.
06 Step 6. Aiven services with VPC peering
Aiven services run in a vendor project. Create the service with a project VPC, then peer that VPC with yours and set the allowed IP filter to your private ranges only.
07 Step 7. Schedule export backups and prove restores
Managed backups cover most cases, but a scheduled logical export to a locked-down bucket protects against logical errors and provider-level loss. Schedule it, then regularly restore into a scratch instance and compare row counts. The same ordered-checks mindset appears in Demolition in Dependency Order: Safe, Re-runnable Offboarding.
// How to verify it works
terraform planon a fresh module call shows no public IP anddeletion_protection = truein the planned instance.gcloud sql instances describe <name>shows no public address and a private IP inside the reserved range.- From a pod in the app network, connect with the credential read from the secret manager; from the internet the instance is unreachable.
- The nightly export object appears in the bucket after the scheduled run.
- Restore the latest export into a scratch instance and compare table row counts with production.
// Design decisions and trade-offs
- One module per database type with a small, opinionated interface, so teams choose size and name and inherit the safe defaults.
- Private connectivity only: no public IPs, with private service access or private endpoints.
- Deletion protection and automated backups on by default, switched off only deliberately.
- Credentials generated by Terraform and written straight to a secret manager, never output or committed.
- Scheduled export backups for services that lack managed point-in-time restore, verified by restoring.
// Pitfalls and lessons learned
- Overlapping CIDR ranges between the reserved service range, the vendor VPC and your own networks, which breaks peering silently.
- Creating many instances before the private connection exists. The module needs an explicit dependency on the peering.
- Passwords in state. Encrypt and restrict the state backend, and rotate by changing the generated value.
- Disabling deletion protection to tidy up and forgetting to re-enable it.
- Opening the allowlist to everywhere to debug and never closing it.
- Backups never restored. The first restore drill finds missing permissions or truncated exports; do it early.
// Frequently asked questions
How do I create a private Cloud SQL PostgreSQL instance with Terraform?
Reserve a private service access range, create the service networking connection, then set ipv4_enabled to false and private_network on the instance, with an explicit dependency on the connection.
How do I keep database passwords out of Terraform outputs?
Generate them with a random resource, write them into a secret manager and output only the secret id. Protect the state because it still contains the value.
How should I connect MongoDB Atlas privately?
Use the cloud provider's private endpoint feature through the Atlas privatelink resources and keep the IP access list empty.
Do managed backups replace scheduled exports?
They cover most failures, but logical exports to separate storage protect against deleted data and provider-level problems. Test restores either way.
// The outcome
A consistent, private, backed-up fleet of database services created from a handful of modules, with sensible defaults and the same review path as the rest of the infrastructure.
// Where to take it next
- Add alerts on storage, connections and replication lag to each module.
- Add read replicas and failover tests to the Postgres module.
- Automate the restore drill in a scheduled pipeline.
- Use Terraform Modules for Cloud Composer, BigQuery Datasets and Pub/Sub to BigQuery Sinks to land data from these stores into analytics.