Choose the Storage or Database Contract Before a Resource Type
Start with the access path, not the service shortlist. Write down what the application actually does to the data: fetch one object by key, join orders to their lines, read one document by id, or scan a month of events. Each answer implies a different unit of consistency, a different Terraform resource and a different restore procedure.
Object storage is a key-and-bytes contract. Cloud Storage returns a whole object or a byte range, with no query language, no partial row update and no transaction across two objects. Overwriting a key creates a new generation instead of mutating the old bytes, which is why versioning is a recovery feature rather than a database replacement.
Cloud SQL is a connection-and-transaction contract. The managed instance speaks MySQL, PostgreSQL or SQL Server over a socket, and the application depends on joins, constraints, indexes and multi-statement transactions. Terraform can create the instance, the database and the users; the tables belong to a migration pipeline.
Document and analytical stores move the unit again. Firestore is a per-document contract with collection queries, and BigQuery is a columnar scan contract where the bill follows bytes read. Spanner keeps relational semantics at global scale, but its primary key and interleaving choices are design decisions that no migration tool can undo.
The resource tree shows the blast radius. A bucket is one resource. A Cloud SQL instance owns its databases, users and backups, so deleting the instance is not a schema rollback. A BigQuery dataset owns its tables and views, and a Firestore database owns its collections.
The flow starts from the access path and stops at the restore unit, because the restore unit is the part teams forget to write down.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["List the access paths
key, query, scan, transaction"] --> B{"Whole object by key
or byte range?"}
B -->|"yes"| C["Cloud Storage
object and generation"]
B -->|"no"| D{"Joins, constraints and
multi-row transactions?"}
D -->|"yes"| E{"Strong consistency
across regions?"}
E -->|"no"| F["Cloud SQL
MySQL, PostgreSQL, SQL Server"]
E -->|"yes"| G["Spanner
relational at global scale"]
D -->|"no"| H{"One document by id?"}
H -->|"yes"| I["Firestore
document and collection"]
H -->|"no"| J["BigQuery
columnar scans and aggregation"]
C --> K["Record the restore unit
before the first apply"]
F --> K
G --> K
I --> K
J --> K
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class A,B,D,E,H primary;
class C,F,G,I,J secondary;
class K ok;
Read the figure as a contract test, not a product ranking. Two teams can legitimately choose different services for the same feature when their read patterns differ. What must not differ is the recorded reason and the restore unit.
The layers are the same for every service; the controls are not. Terraform owns the container in all five cases, the service owns retention and availability, and the stored bytes sit below every plan.
| Contract signal | Cloud Storage | Cloud SQL | Firestore | BigQuery |
|---|---|---|---|---|
| Unit of change | object and generation | row and transaction | document | partition or table |
| Read path | key or byte range | SQL over a connection | document id or collection | columnar scan |
| Terraform creates | bucket, IAM, lifecycle | instance, database, user | database and indexes | dataset, table, view |
| Restore unit | generation or soft-deleted copy | clone at a timestamp | export or point-in-time copy | snapshot or time travel |
| One-way change | locked retention period | instance delete | database delete | dataset delete |
Record the choice in the repository. A short decision record naming the access paths, the service, the restore unit and the irreversible change is worth more than a comparison table in a slide deck.
Manage Bucket IAM, Encryption and Retention Carefully
The bucket name is the identity, and it is fixed for the life of the bucket. Bucket names are globally unique, the location is chosen at creation, and a rename in configuration is a destroy and create. Put project, environment and purpose in the name, then keep the team label in labels, which is mutable.
Uniform bucket-level access removes the second permission system. With uniform_bucket_level_access = true every grant is an IAM binding at bucket or project level, and object ACLs stop applying. Enabling it on a bucket that still relies on ACLs locks those callers out, so inventory the existing grants before the apply.
IAM resources are not interchangeable. A google_storage_bucket_iam_member adds one principal and leaves every other grant alone. A binding or policy resource is authoritative for its scope and removes anything it does not list, including grants made in the console.
Public access prevention is a separate switch from IAM. Setting public_access_prevention = "enforced" refuses public principals even if a later binding tries to add them. Keep the organization policy as the outer guardrail, because a bucket-level setting can be changed by whichever root owns the bucket next.
Encryption defaults are fine until a compliance rule says otherwise. Google encrypts every object at rest; a CMEK through encryption.default_kms_key_name adds a key you control and a key IAM dependency. Customer-supplied keys put key material in configuration and state, so treat them as a last resort rather than a hardening step.
Versioning turns an overwrite into two generations. The live object keeps the name, the previous bytes become a noncurrent generation, and a delete without a generation makes the live version noncurrent. Versioning is what makes an accidental overwrite recoverable, and it also multiplies storage cost until a lifecycle rule removes old generations.
Lifecycle rules are asynchronous cleanup, not a retention guarantee. A rule combines conditions with AND and runs its action later, often within a day. An age condition on a live object will delete the only copy, so pair deletion rules with a noncurrent state or a prefix that only matches derived data.
Retention is the one setting that can outlive your ability to change it. A retention_policy blocks deletion and overwrite for the period, and setting is_locked = true makes the policy permanent: the period can grow and never shrink. Lock only after the period has passed legal review and a restore drill.
Soft delete is a shorter, separate window. The default keeps deleted objects for seven days, the policy accepts 7 to 90 days, and retention_duration_seconds = 0 turns it off. Soft-deleted bytes still count as stored bytes, so a long window is a cost decision as well as a recovery decision.
Object holds are per object and need the feature enabled. temporary_hold and event_based_hold protect individual objects from deletion, and both require object retention on the bucket. A hold is not a backup: releasing it puts the object back under the normal lifecycle.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["Bucket name and location
fixed at creation"] --> B["uniform_bucket_level_access = true"]
B --> C{"Any caller still relies
on object ACLs?"}
C -->|"yes"| C1["Failure: grants stop applying
and the caller gets 403"]
C -->|"no"| D["public_access_prevention = enforced"]
D --> E{"Compliance requires
a retention period?"}
E -->|"yes"| F["retention_policy
retention_period in seconds"]
F --> G{"Period reviewed and
restore drill passed?"}
G -->|"no"| G1["Wait: is_locked cannot
be undone"]
G -->|"yes"| H["Set is_locked = true
the period can only grow"]
E -->|"no"| I["soft_delete_policy
7 to 90 days, 0 disables"]
H --> J["versioning enabled"]
I --> J
J --> K["lifecycle_rule with Delete
or SetStorageClass"]
K --> L{"Rule targets live objects
by age alone?"}
L -->|"yes"| L1["Failure: the only copy is
deleted on schedule"]
L -->|"no"| M["Target noncurrent versions
or a known prefix"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class A,B,D,E,G,J,K primary;
class F,H,I,M secondary;
class C1,L1 danger;
class G1,L warn;
Read the failure branches as the review checklist. Each one is a setting that looks correct in a diff and only misbehaves once data exists.
Connect Cloud SQL Through the Selected Private and Identity Path
Provisioning, database objects and application access are three layers with three owners. The platform root creates the instance and its network path; a migration job creates the database and users; the application owns its connection and credentials. Collapsing all three into one apply is how a schema change becomes an outage.
Private IP is a peering path, not a firewall rule. Setting private_network and disabling the public address attaches the instance to the VPC through the service networking peering that the network root already created. The instance does not read the peering resource, so an explicit depends_on prevents a first-apply race.
The private path must be reachable from where the workload runs. An instance in the host project of a Shared VPC is reachable from service project subnets, but a client in another VPC needs peering or Private Service Connect. Test from the workload subnet; a timeout usually means the route, not the password.
Private Service Connect trades peering for an endpoint. With psc_config enabled and the consumer project allowed, the consumer creates a forwarding rule and reaches the instance through a private address it owns. That is the cleaner path when the network teams belong to different organizations, because no CIDR overlap has to be negotiated.
A public address is a deliberate exception. If one exists, restrict it with authorized_networks and force TLS with ssl_mode = "ENCRYPTED_ONLY". Anything else is a database reachable from the internet with a password as its only control.
Enforce the connector when IAM should be the only front door. connector_enforcement = "REQUIRED" rejects direct connections, so every session arrives through a connector that has already proved the caller identity. The database grant still decides what that session can read.
IAM database authentication removes the password from the connection string. Turn on the IAM flag, create the user with an IAM type, and grant the instance-level role to the principal. The database still needs its own grant: authentication proves who connected, and the SQL privilege decides what the session may read.
High availability and recovery are configuration, not an afterthought. availability_type = "REGIONAL" gives a standby, but backups still need to be enabled, and PostgreSQL point-in-time recovery needs its own switch. A standby survives a zone failure; it does not undo a bad DELETE.
Backup settings have two clocks. Automated backups keep a count of retained backups, while transaction logs cover the point-in-time window: one to seven days on Enterprise, and up to 35 on Enterprise Plus. Write both numbers into the runbook, because they answer different questions.
Flags are engine settings with restart costs. Values live in settings.database_flags, and some changes restart the instance during the maintenance window. Use flags for engine behaviour such as slow-query logging, never as a substitute for a schema migration.
Two deletion controls protect different surfaces. deletion_protection blocks Terraform from destroying the instance, while the service-side setting blocks deletion through every surface including the console. Set both for a production database, and expect a deliberate two-step apply when it is finally retired.
The edition default is a trap for small instances. PostgreSQL 16 and later default to Enterprise Plus, which accepts only performance-optimized tiers, so a shared-core tier fails at create unless edition = "ENTERPRISE" is set. Read that plan error as a configuration mismatch, not as a capacity shortage.
Version SQL and Dataset Changes Outside Infrastructure Ownership
Terraform creates an empty database. A google_sql_database sets the name, charset and collation and nothing else; the first table arrives from a migration. The same is true of a BigQuery dataset and a Firestore database: the container is infrastructure, the contents are application state.
The migration runner owns the schema and keeps its own ledger. Numbered forward-only files, a ledger table inside the database, and one pipeline allowed to apply them. The invariant is that the database records what ran, not that Terraform state does.
Order the release as infrastructure, then migration, then code. Terraform can order the instance before the database, but it cannot place your SQL between the database and the application. A release that ships the new query and the new column together has a window where the query fails.
A provisioner is not a migration system. A local-exec step hides an imperative command inside a declarative apply, has no ledger, and re-runs when the resource is replaced. Keep migrations in a job whose success is visible in the database.
Expand, migrate, contract, and never rename in one release. Add a nullable column, deploy code that writes both shapes, backfill in batches, switch reads, then drop the old column later. The overlap is what makes a rollback a code action instead of a restore.
Terraform is the wrong tool for bulk objects. The object resource keeps content in state and reads source from the machine that runs the apply, so it suits a bootstrap file, not a nightly export. Bulk data belongs to a pipeline using the storage CLI or Storage Transfer Service, with checksums and a manifest.
An object upload is a new generation, so publish by pointer. Write the new export under a versioned prefix, verify its checksum, then update the small manifest that readers resolve. Overwriting the live key in place gives readers a torn view and leaves no clean rollback target.
Dataset loads follow the same ownership rule. A BigQuery load job or scheduled query writes partitions; Terraform declares the dataset, tables and IAM. Mixing the two produces a table whose schema is half-declared and half-evolved, and neither owner can explain the current shape.
The figure contrasts the release that couples writers with the sequence that keeps one ledger.
The left panel is the failure the ledger prevents. Without a recorded order, nobody can tell whether the column or the code arrived first, so the recovery step is guesswork.
Prove Recovery and Review Delete Protection
A backup is a copy; a restore is a procedure. Retention tells you what the service kept. Only a restore into a scratch target, timed and queried, proves the copy is usable, and only a written result survives the next staff change.
Each service restores differently, and the difference matters. Cloud SQL point-in-time recovery clones into a new instance, a backup restore can overwrite a target, and a Cloud Storage recovery copies a noncurrent generation or restores a soft-deleted object. None of them rewinds production in place.
Do not make restore part of the Terraform graph. The provider exposes clone and restore blocks, but they trigger an imperative action during create or update. Run restores as an explicit operator step, then decide whether to rewire the application or promote the copy.
Delete protection has three independent layers. The bucket's destroy flag decides whether Terraform empties it first, the instance's protection stops a Terraform destroy, and the service-side setting stops deletion through every surface. A lifecycle rule adds a fourth and fails the plan before the API call.
Some changes have no undo at all. Locking a bucket retention policy, changing a bucket's name or location, and deleting a Cloud SQL instance are one-way operations. Put each one behind a review that names the data it would destroy.
The lab below is the trace to run before trusting any of it.
Prove Recovery and Review Delete Protection
Execution status: design-only. This trace was written against Terraform 1.17.1 and hashicorp/google 8.10.0 on 6 November 2026. It was not run against a live project, so every expected result below is documented behavior rather than a measurement.
Prerequisites. A disposable project, the VPC and service networking connection from the networking part, a bucket with versioning enabled, and a Cloud SQL PostgreSQL instance with backups and point-in-time recovery on. Use the smallest tier the chosen edition allows.
- Baseline the root. Apply, then plan again and expect no changes. Record the backup retention days, the soft-delete window and the bucket location.
- Write one known object and one known row. Note the UTC time of both writes; that timestamp is the restore target, not the time on your laptop.
- Overwrite the object. Confirm the previous bytes exist as a noncurrent generation by listing all versions.
- Restore the object. Copy the noncurrent generation to a scratch key and compare its checksum with the recorded value.
- Clone the database. Request a point-in-time clone at the recorded time and expect a new instance with a new connection name.
- Query the clone. The known row must be present, and the original instance must still be serving.
- Delete the scratch copies. Remove the clone and the scratch key, then check what the service still retains and for how long.
- Read the destroy plan. Run a plan with the destroy flag and list every data resource before approving anything.
| Observation | Passing result | Failing result means |
|---|---|---|
| Object after overwrite | previous bytes reachable as a generation | versioning was never enabled |
| Restored object checksum | matches the recorded value | the restore copied the wrong generation |
| Clone endpoint | new instance, original untouched | the restore was treated as an in-place edit |
| Known row in the clone | present at the chosen time | the timestamp was after the write |
| Destroy plan | every data resource listed | the plan was approved from the summary |
Cost dimensions. The clone bills for its tier and disk for the hours it exists, noncurrent and soft-deleted objects bill as stored bytes, and any egress from a restore is charged. Delete every scratch resource the same day.
Sources. Bucket lock and retention follow the Cloud Storage retention documentation, lifecycle behavior follows the Object Lifecycle Management documentation, and point-in-time recovery follows the Cloud SQL backup documentation.
Next in the Series
In Cloud Run and Event Delivery: Artifacts, Service Identities and Triggers, we'll explore Promote serverless application versions and connect events without broadening invocation or data access.