A database created in ten minutes can remain an operational liability for years if nobody owns its upgrades, recovery tests, access reviews, or retirement.

TL;DR

  • Problem: Shipping a reusable Terraform module without an operational contract leaves ownership, destructive replacements, state blast radius, and application schema migrations undefined at fleet scale.
  • Answer: Pair versioned Terraform modules with isolated per-workload GCS state, two-layer deletion protection, Shared VPC host/service project boundaries, and separate application-owned DDL pipelines.
  • Watch out: Terraform’s deletion_protection only guards the provider unless settings.deletion_protection_enabled and lifecycle { prevent_destroy = true } are also enforced, and blind drift auto-apply will overwrite emergency on-call fixes.

Ownership continues after provisioning

Situation

A database platform team often begins with a practical goal: application teams should be able to request a managed PostgreSQL deployment without filing tickets for every instance, backup policy, private IP allocation, and monitoring alert. Terraform modules and a CI/CD deployment pipeline make repeatable provisioning across Google Cloud projects straightforward.

The platform’s product, however, is not the Terraform module alone. It is the contract combining supported configurations, explicit ownership boundaries, service objectives, safe upgrade paths, operational evidence, and an exception process. Without that contract, self-service provisioning accelerates fleet growth faster than the organization can govern it.

In a multi-project Google Cloud estate using Shared VPC, this gap becomes visible immediately. Network resources live in a central host project, database instances run in management or service projects, and application workloads connect from GKE or Compute Engine in separate service projects. A module that creates a google_sql_database_instance in isolation does not answer who manages Private Services Access IP ranges, who rotates credentials, or who runs the restore drill when an application team accidentally truncates a table.

The Problem

A Terraform module can pass terraform apply cleanly and still leave four operational failure modes unresolved across the database lifecycle.

Constraint 1: Blast radius and state lock contention. When a platform team stores multiple projects or production databases inside a single Terraform state file, every plan and apply acquires a single .tflock lock object in Google Cloud Storage (GCS) via atomic x-goog-if-generation-match: 0 preconditions. Beyond serialization bottlenecks, an unpinned module update or accidental state corruption affects every database in that state file simultaneously. Bounding blast radius requires isolating state per workload and environment (for example, one state prefix per service-environment pair).

Constraint 2: Destructive force new replacements. Changing immutable attributes on google_sql_database_instance—such as certain network settings, major version properties, or instance identifiers—causes Terraform to plan a destroy-and-recreate (-/+) operation. On newer Google provider versions, deletion_protection defaults to true at the provider level, which blocks terraform destroy or forced replacement, but relying on a single flag is fragile. If an engineer sets deletion_protection = false in a pull request to unblock a refactor, Terraform will delete the production database unless both GCP-level settings.deletion_protection_enabled and Terraform’s lifecycle { prevent_destroy = true } are enforced.

Constraint 3: Plaintext secrets and unversioned state in GCS. Terraform state files store resource attributes in plaintext, including bootstrap passwords, connection strings, and private IP topologies, even when outputs are marked sensitive = true. Anyone with Storage Object Viewer or Storage Object Admin on the state bucket can run terraform state pull and read those values. State buckets therefore require strict IAM isolation, object versioning (gsutil versioning set on), and Customer-Managed Encryption Keys (CMEK) via Cloud KMS where compliance demands key control.

Constraint 4: Cross-project Shared VPC IAM boundaries. In Google Cloud’s Shared VPC model, Private Services Access (VPC Network Peering to Google’s service networking producer network) and servicenetworking.googleapis.com peering allocations (such as a /24 or larger CIDR block) must be configured in the Host Project, along with central firewall rules. Meanwhile, client workloads in attached Service Projects cannot attach network interfaces or route traffic across the shared subnets unless their service accounts or principals hold roles/compute.networkUser on the host project or target subnets.

Unbounded Terraform modules multiply blast radius across projects

How do you turn repeatable Terraform provisioning into a governed database service that remains safe through upgrades, drift, and recovery?

Options Considered

Platform teams generally choose among four operating models when scaling managed databases across multiple projects.

OptionProvisioning SpeedBlast RadiusGovernance & SafetyPrimary Rejection or Selection Reason
Central DBA ticket queueSlow (days to weeks)Low (manual review)High consistency, poor audit trailRejected because manual tickets bottleneck delivery and invite shadow IT
Copy-pasted HCL templatesFast initial setupIsolated per repoSevere drift; inconsistent backups/HARejected because security patches and flag updates never reach existing repos
Monolithic platform stateModerateHigh (fleet-wide lock/failure)Centralized policy, fragile appliesRejected due to .tflock contention and multi-tenant blast radius
Versioned product contractFast via CI/CDBounded per workload/envHigh (pinned modules + policy + isolated state)Recommended: balances self-service speed with lifecycle safety

A central ticket queue gives DBAs tight control over instance sizing and backup settings, but it turns the database team into a deployment bottleneck. Application teams respond by requesting broad project-level IAM roles to provision databases manually in the Cloud Console, bypassing platform standards altogether.

Distributing copy-pasted Terraform templates into application repositories solves the ticket bottleneck, but it destroys fleet governance. Within months, teams diverge on deletion_protection, PITR retention, and monitoring alerts, and rolling out a mandatory provider or TLS policy upgrade requires opening dozens of manual pull requests across repositories you do not own.

A monolithic Terraform state—where the platform team manages 50 or 100 databases from one root module—centralizes governance at the cost of availability. A single broken resource data source or stuck .tflock blocks unrelated teams from deploying, and a careless module refactor risks planning changes across every production database at once.

The recommended approach is a versioned product contract: the platform team publishes semantically versioned Terraform modules with strict input schemas, application teams consume pinned versions in isolated per-workload GCS state prefixes, and policy checks in CI verify every plan before apply.

Productized modules beat ticket queues and unguarded self-service

Define the Product Contract Before the Module

A database platform contract explicitly separates three operational planes: the network plane, the database infrastructure plane, and the application schema plane.

Separate network, database infrastructure, and application schema planes

Product inputs and fleet inventory

A platform intake contract should ask application teams for workload attributes they actually know: service owner, escalation channel, environment (dev, staging, prod), region, data classification, RPO/RTO tier, expected storage and connection count, and required PostgreSQL version or extensions. It should not force application engineers to pick raw Shared VPC peering ranges or backup window cron expressions.

Inventory tracking must distinguish physical and logical units accurately. A PostgreSQL logical database, a Cloud SQL instance, an AlloyDB cluster, an AlloyDB read-pool instance, and a Google Cloud project are separate billing, quota, and failure objects. Counting “databases” without separating instances from logical schemas corrupts capacity planning and cost attribution.

The ownership matrix below defines explicit primary owners and required collaboration points:

ResponsibilityPrimary OwnerRequired Collaboration
Shared VPC, PSA peering, Private DNSNetwork platformDatabase and application teams
Database module, HA, backups, flagsDatabase platformApplication owner for tier selection
Application DDL and schema migrationsApplication teamDatabase platform for lock guardrails
Database roles and object privilegesJointly definedIdentity and application owners
Backup policy and PITR restore drillsNamed service ownerPlatform provides runbook and tooling
Incident response and communicationNamed service ownerPlatform on-call for infra escalation

Codify two-layer deletion protection and GCS state

Every production module must enforce both provider-level and GCP-level deletion locks alongside an isolated GCS backend. In Terraform, deletion_protection blocks the Google provider from issuing a delete call, while settings.deletion_protection_enabled blocks deletion at the GCP API/Console layer, and lifecycle { prevent_destroy = true } aborts any plan that attempts replacement:

terraform {
  backend "gcs" {
    bucket = "org-db-tfstate-prod"
    prefix = "workloads/orders-api/prod"
  }
}

resource "google_sql_database_instance" "primary" {
  name                = "orders-api-prod-pg16"
  database_version    = "POSTGRES_16"
  region              = "us-central1"
  deletion_protection = true

  settings {
    tier                        = "db-custom-4-16384"
    deletion_protection_enabled = true
    availability_type           = "REGIONAL"
  }

  lifecycle {
    prevent_destroy = true
  }
}

Protect the org-db-tfstate-prod bucket with object versioning, CMEK encryption, and restricted IAM so only the Workload Identity Federation (WIF) deployment principal—never long-lived static service account keys—can mutate production state. If a CI runner crashes mid-apply and leaves a stale .tflock object in GCS, require an explicit incident ticket before running terraform force-unlock <LOCK_ID> so two concurrent applies never race on state mutations.

Separate infrastructure from application schema

Terraform is designed for declarative infrastructure state, not transactional application schema evolution. Putting CREATE TABLE or ALTER TABLE statements inside Terraform resources couples database DDL locks to infrastructure applies and breaks zero-downtime application rollouts. Furthermore, PostgreSQL ALTER TABLE operations that acquire ACCESS EXCLUSIVE locks will queue all concurrent reads and writes behind any long-running analytical query unless the migration runner sets lock_timeout and statement_timeout explicitly.

Application teams should own schema migrations using dedicated migration tooling (such as Flyway, Liquibase, or Alembic) integrated into application CI/CD. For breaking changes like column renames or type changes, teams must use an expand-and-contract workflow: add the new column, deploy application code that dual-writes and reads safely, backfill historical rows in batches, verify read adoption, and drop the legacy column in a later release. The platform’s role is to provide isolated migration credentials, a staging clone for lock testing, and connection-timeout guardrails—not to embed application DDL inside terraform apply.

How It Rolls Out

Treating module versions as a public API requires a four-stage rollout workflow with explicit validation gates and realistic rollback boundaries.

Staged module rollouts catch destructive plans before production

Stage 1: Plan inspection and policy gate

Consumers pin exact module versions (for example, version = "~> 2.4.0") in their workload repositories. When a module upgrade PR opens, CI runs terraform plan and evaluates the JSON plan against policy rules (such as OPA/Conftest). Any plan containing a delete or replace (-/+) action on a database instance fails the gate automatically unless accompanied by an explicit break-glass approval and documented migration plan.

Stage 2: Nonproduction apply and upgrade test

Before tagging a module release as production-ready, apply the new version to a representative nonproduction state that mirrors production topology (Shared VPC attachment, HA enabled, read replicas, and existing data). This verifies that state migrations—such as moved blocks or renamed resource attributes—execute in-place without triggering unintended replacement or downtime.

Stage 3: Canary production cohort

Roll the validated module release to a small cohort of tier-2 production workloads first. Monitor connection counts, replication lag, query latency, and Cloud Monitoring alerts for a 24-hour soak window. Track module version adoption across the fleet so legacy module versions do not linger indefinitely with unpatched security or backup defaults.

Stage 4: Fleet adoption and recovery verification

Expand rollout across remaining production cohorts in waves, updating the fleet inventory with the active module version and the timestamp of the last verified restore drill. Understand the rollback boundary clearly: reverting a Git commit can roll back a Terraform flag change, but it cannot un-upgrade a major PostgreSQL engine version or recover dropped data. True rollback for destructive database changes relies on PITR clones or pre-upgrade snapshots, never Git history alone.

In Practice

Google Cloud’s Shared VPC architecture illustrates why platform contracts cannot stop at the database module boundary. In Google’s documented Shared VPC model, the host project owns the VPC network, subnets, firewall rules, and Private Services Access peering connection (servicenetworking.googleapis.com), while service projects attach to those shared subnets using roles/compute.networkUser. A database provisioning pipeline that only operates inside a single application service project will fail to configure private IP connectivity unless the platform interface explicitly coordinates host-project peering and subnet permissions.

Similarly, Terraform’s documented behavior for google_sql_database_instance reinforces why two-layer protection and staged applies are mandatory. When an engineer intentionally needs to replace a protected instance, setting deletion_protection = false in HCL is not a single-step delete: Terraform must first apply the state update to disable protection (or remove prevent_destroy) before a subsequent apply can destroy or replace the instance. That two-step friction is intentional—it prevents a hurried refactor from wiping a production database in one command.

To validate a platform contract end to end before onboarding teams, execute a concrete acceptance test on one nonproduction service: submit an intake request, run policy validation on the generated terraform plan, apply via Workload Identity Federation, inject a controlled drift change (such as a manual flag edit in Console) to verify drift detection without blind overwrite, and time a full PITR restore including application reconnection and DNS resolution.

Where It Breaks

ConditionBreaks howDetectMitigate
Missing owner metadata at intakeIncidents and quota alerts stall with no escalation pathInventory audit finds untagged instancesRequire owner and pager_channel labels in module schema
Unprotected force new plan appliedImmutable attribute edit destroys live databaseCI plan diff shows -/+ replacementEnforce deletion_protection, deletion_protection_enabled, and prevent_destroy
Monolithic state locks across teamsOne slow apply blocks all teams via .tflockCI jobs queue waiting on GCS lockSplit GCS backend prefixes per workload and environment
Plaintext secrets exposed in stateUsers with bucket read access pull DB credentialsIAM audit shows broad storage.objectViewerRestrict GCS IAM, enable CMEK, and use WIF + Secret Manager
Blind scheduled drift reconciliationAuto-apply reverts an emergency on-call flag fixDrift detector triggers silent overwriteAlert on drift and require human review before reconciling
App DDL embedded in TerraformTable locks or schema mismatch break live app podsterraform apply hangs on lock waitMove DDL to app migration pipelines with expand-and-contract
Restore drill tests DB creation onlyInstance boots, but IAM, DNS, and app fail to connectChaos drill measures infra time, not app RTORequire end-to-end app health check in quarterly restore drills
Shared VPC permissions missingApp pods in service project cannot reach private IPConnection timeouts from service subnetsGrant roles/compute.networkUser and verify host firewall rules

Lifecycle gaps turn routine Terraform runs into fleet outages

Key Takeaways

  • A database platform is an operational contract—covering ownership, upgrades, drift, and recovery—not a standalone Terraform module.
  • Isolate Terraform state per workload and environment in GCS with object versioning, CMEK, and .tflock locking to bound blast radius.
  • Enforce three layers of protection (deletion_protection = true, settings.deletion_protection_enabled = true, and lifecycle { prevent_destroy = true }) on every production database instance.
  • Separate Shared VPC host-project networking (servicenetworking.googleapis.com and firewall rules) from service-project compute (roles/compute.networkUser) and application-owned DDL migrations.
  • Treat drift as an investigation signal rather than an automatic overwrite instruction, and measure recovery drills by end-to-end application restoration time.

What to Do Next

  • Problem: Audit your existing Cloud SQL and AlloyDB fleet for unowned instances, shared monolithic Terraform state files, and missing deletion-protection locks.
  • Solution: Publish a versioned module contract that separates network ownership, database infrastructure, and application schema migrations.
  • Proof: Run an end-to-end acceptance test on one nonproduction workload—covering CI plan policy checks, drift detection, module upgrade, and a timed application-level PITR restore.
  • Action: Add module version tracking, owner labels, and last-restore-drill timestamps to your fleet inventory this week.

Sources to Verify