Cloud / IaC · Earlier generation

The GCP Project Factory: Folder, Project, VPC and GKE per Tenant

An earlier-generation Terraform estate that onboards a team or customer on GCP with a folder, main and sub-projects, private networking, data services and GKE.

  • Terraform
  • GKE
  • Shared VPC
  • Pub/Sub
  • BigQuery
  • Cloud SQL
  • Anthos Service Mesh
  • OPA Gatekeeper
  • Vault
  • Cloudflare

// Why this matters

A GCP project factory with Terraform answers a recurring platform question: how do you give every team or customer a consistent, private-by-default home without hand-building it each time? The project is GCP's natural isolation unit (IAM, quotas, billing labels, API enablement), and a folder above it is the natural place to attach organisation policy and group access.

This is the earlier generation of the platform that the Azure pipeline in From Form to Running Cluster: Self-Service Team Onboarding later improved on. It is worth documenting because the shape it settled on (folder, factory project, private network, data services, clusters, follow-on roots) survived the move between clouds, and because several of its mistakes are instructive.

The motivation is the same as everywhere in this series: remove the human from the repetitive path, make naming and network defaults deterministic, and make every tenant look the same to operators and to security review.

// The problem

Without a factory, tenant environments are bespoke. Projects end up with default networks and external IPs, service accounts with project-wide roles, and a Cloud SQL instance reachable from the internet because that was the quickest way to connect. Each is individually fixable, and collectively they are unauditable.

There is also a structural problem on GCP: shared VPC. If the tenant needs to join a host project's network, the service project has to be attached with the right subnet-level IAM, and getting the list of subnets wrong is silent until a node pool fails to create. Provisioning also needs organisation-level roles (create folders and projects, attach billing), which you do not want held by a human.

Finally, sizing and topology vary per tenant: one cluster or two, which regions, how many nodes at most, whether to enable mesh. If those are Terraform variables edited per tenant, the code forks. They have to be data.

// The solution

Each tenant root has the same shape. A folder module creates the tenant folder under a lower or upper parent. A project factory module creates the main project (and any secondary projects) inside it, activating a list of APIs, setting labels, optionally attaching it as a shared-VPC service project, and optionally binding an admin group. A VPC module builds the tenant network with a subnet list, firewall rules module, and a private service access range so managed services can use private IPs.

Configuration is data. A single Vault path per tenant is listed and read in bulk, and each structured setting (buckets, Postgres instances, topics, BigQuery datasets, cluster settings) is a JSON key decoded with jsondecode and expanded with for_each. A size class chosen at request time sets the maximum node counts for the cluster. Optional capabilities are enabled by key presence or an enabled field in the JSON, so the same root builds a tenant with or without a dataset.

Privacy is enforced by construction. External IPs are disabled on services, Cloud SQL uses a private network, GKE nodes are private with workload identity, and secondary projects reach the main project through cross-project IAM bindings rather than copied credentials. A dedicated provisioning identity holds the org-level roles and is granted them by a separate group script, never by the tenant roots.

After the primary cluster exists, a null_resource dispatches the policy-controller workflow for that cluster, and an HA flag decides whether the second cluster, mesh and autoscaling modules exist at all. Companion roots handle autoscaling, service mesh and DNS records. Alternatives I rejected: one giant monolithic project for all tenants (no isolation), and Deployment Manager or console clickops (no review, no state). The honest lesson I would take forward is to key clusters by region with for_each from the start rather than repeating a near-identical block per region, which is what the Azure generation did (see Adding a Region Without Destroying Anything).

How it flows flow1. Config read → 2. Folder and projects → 3. Network → 4. Data services → 5. Compute → 6. Gate: policy dispatch → 7. Follow-on roots01Config read02Folder and projects03Network04Data services05Compute06 · GATEGate: policy dispatch07Follow-on roots
How it flows. End-to-end flow. Dashed pink nodes are gates: points where a human or a check must pass before the next stage runs.
  1. Config readtenant values read from Vault
  2. Folder and projectsfolder, main project and secondary projects from factory modules
  3. Networktenant VPC, optional shared-VPC host attachment, private service access
  4. Data servicesbuckets, topics, dataset, private-IP-only PostgreSQL
  5. Computeprivate-node GKE clusters with workload identity, sized by class
  6. Gate: policy dispatch gateadmission-control workflow triggered for the new cluster
  7. Follow-on rootsautoscaling, service mesh for HA, DNS records from Vault-held lists
HierarchyParent folderTenant folderMain + secondary projectsNetworkTenant VPCShared VPC attachmentPrivate service accessFirewall rulesData servicesBucketsPub/Sub topicsDatasetPrivate-IP PostgresComputePrivate GKE (1 or 2)Workload identityPolicy controller
One tenant, four layers. The tenant root builds the same stack every time; only the data differs.
Provisioning order flow1. Read config → 2. Folder and projects → 3. Network → 4. Data services → 5. Compute → 6. Gate: policy dispatch → 7. Follow-on roots01Read config02Folder and projects03Network04Data services05Compute06 · GATEGate: policy dispatch07Follow-on roots
Provisioning order. Each stage consumes outputs of the previous one; the dispatch hands over to a separate workflow.
  1. Read configbulk read tenant keys from Vault
  2. Folder and projectsfactory modules, APIs, labels
  3. NetworkVPC, subnets, firewall, private service access
  4. Data servicesbuckets, topics, dataset, private Postgres
  5. Computeprivate GKE sized by class
  6. Gate: policy dispatch gategatekeeper workflow triggered per cluster
  7. Follow-on rootsautoscaling, mesh for HA, DNS records

// Before you start

  • A GCP organisation with a lower and an upper parent folder, a billing account, and a provisioning service account with folder-creator, project-creator and billing-user roles granted at the right level.
  • Terraform 1.5+ with the Google and Google-beta providers, and a remote state bucket per estate.
  • HashiCorp Vault holding a per-tenant secret path (or any key-value store that Terraform can read in bulk).
  • The Compute, Container, Service Networking, Cloud SQL Admin and Cloud Resource Manager APIs enabled on the project that runs the pipeline.
  • An existing host project if you want shared VPC, with its subnets pre-created and listed.

// Step-by-step implementation

  1. 01 Read the tenant configuration in bulk from Vault

    Start with the data contract. List every secret under the tenant path and read each one, then build a flat map. All later modules take their inputs from local.customer_values. This is the same pattern used on the Azure generation (see Vault as the Control Plane: A Five-Tier Key Model with Locking) and is what lets one root serve every tenant.

    Wrap the list in nonsensitive() because Terraform marks the whole result sensitive and you cannot for_each over a sensitive set. The key names are not secret; the values stay sensitive in the data sources.

  2. 02 Create the folder and the project factory

    The folder module creates the tenant folder under a configured parent. The project factory creates the main project inside it with a deterministic name (prefix plus environment), an API activation list from config, labels, and optionally attaches the project as a shared-VPC service project. Decide random_project_id deliberately: random suffixes avoid global ID collisions after a delete (project IDs are not reusable immediately), at the cost of IDs you cannot predict, so every consumer must reference the module output, never rebuild the string.

    Set disable_services_on_destroy and disable_dependent_services from config rather than hard-coding; a factory that disables services on destroy can break a project that is only being moved.

  3. 03 Build the private network: VPC, firewall and private service access

    The tenant VPC is created from a subnet list in config, with per-subnet flags for private Google access and flow logs, and a logging config. Create the firewall rules in a separate module that depends on the project so the network exists first. Reserve a private service access range and create the peering; this is what lets Cloud SQL and other managed services get private addresses in your network.

    Delete the default routes only if you are certain about egress; otherwise leave them and control egress with firewall rules. Keep routing_mode explicit; a regional VPC and a global one behave very differently once a second region exists.

  4. 04 Create data services as JSON-driven for_each, with private IPs only

    Buckets, Cloud SQL instances, topics and datasets are all lists in JSON config, expanded with for_each. This is the payoff of treating config as data: adding a second Postgres instance for a tenant is a Vault edit. Make optional services conditional on an enabled field in the JSON.

    Cloud SQL deserves care. Set ipv4_enabled = false and a private_network pointing at the tenant VPC, so the instance has only a private address (the private service access range makes this possible). Make the module depend on the VPC so the peering exists first. Keep deletion_protection as a deliberate choice per environment; in lower you may want it off, in upper never.

  5. 05 Create a private-node GKE cluster sized by class, with workload identity

    The cluster module reads a size class from config and maps it to a maximum node count. Keep the mapping in a locals lookup so it is reviewable. Use private nodes, workload identity (workload_pool = <project>.svc.id.goog), and authorized master networks from config. Create one service account per workload identity binding with a narrow role set and the namespace and Kubernetes service account it is bound to.

    Note the Terraform restriction that bit the original: an IAM member resource takes one role as a string, not a list, so multiple roles require multiple resources or a for_each over role/member pairs. Use for_each over a flattened list rather than copy-pasting the resource.

  6. 06 Dispatch the policy-controller workflow after the cluster exists

    Admission control (OPA Gatekeeper in this estate) must be installed after the cluster and cannot be installed by the Terraform that creates it without the Kubernetes provider fighting the cluster lifecycle. Use the same technique as the Azure generation: a null_resource that depends on the cluster and POSTs a workflow_dispatch for a dedicated workflow with the cluster coordinates as inputs.

    Gate it on the cluster existing (the count on the cluster module) and on a token being present, and use curl --fail so a rejected dispatch fails the apply instead of silently skipping policy. The lesson from the original: it had one such resource per region, copy-pasted; make it a for_each over clusters.

  7. 07 Add HA and follow-on roots: autoscaling, mesh, DNS from a Vault list

    Gate the second cluster, the mesh module and the autoscaling module on an ha_enabled flag so non-HA tenants never have those resources. Keep autoscaling, mesh and DNS as separate roots with their own state, because they use different providers and have different change cadence; they read the tenant keys and the cluster outputs written back to Vault.

    DNS records derive from a Vault list. Filter out incomplete entries (a record with no target) before for_each, or a half-edited list breaks the whole plan. Build the key from name and type so reordering the list does not recreate records.

// How to verify it works

  • gcloud projects list --filter="parent.id=<folder-id>" shows the tenant main (and secondary) projects under the tenant folder.
  • gcloud compute instances list and gcloud container clusters describe show no external IPs, privateClusterConfig.enablePrivateNodes: true, and a workload pool set.
  • gcloud sql instances describe <instance> --format="value(settings.ipConfiguration.ipv4Enabled)" returns False, and the instance has a private IP only.
  • The policy workflow run appears in the Actions list after the apply, and kubectl get constrainttemplates lists templates once it finishes.
  • terraform plan after apply shows no changes; edit one Vault JSON key and confirm only the corresponding module changes.

// Design decisions and trade-offs

  • Internal IPs only; external IPs disabled across services.
  • A dedicated provisioning identity holds org-level roles, granted by a separate group script.
  • Secondary projects use cross-project IAM bindings rather than copied credentials.
  • DNS records derive from a Vault list with filtering of incomplete entries.
  • An HA flag decides whether the second cluster, mesh and autoscaling modules exist.

// Pitfalls and lessons learned

  • Random project IDs rebuilt by string. Always reference module.<project>.project_id; a rebuilt ID points at a different project.
  • Sensitive-set errors on for_each. Wrap the Vault key list in nonsensitive().
  • Cloud SQL private IP before the peering exists. The module needs depends_on for the VPC and private service access, or creation fails with a network error.
  • Copy-pasted per-region cluster and dispatch blocks. They drift; use for_each over a regions map from the start.
  • Multiple roles in one IAM member resource. The role argument is a string; flatten to role/member pairs.
  • Shared-VPC subnet lists that omit a region. Node pool creation fails late with a permissions error on the subnet.
  • Org-level roles on the pipeline identity granted ad hoc. Grant them with a separate script run by a human admin and audit that group.

// Frequently asked questions

What is a GCP project factory?

A set of Terraform modules that create a tenant folder and project with consistent APIs, labels, networking and IAM, so every tenant is built the same way from configuration.

How do I make Cloud SQL private-IP only with Terraform?

Reserve a private service access range, create the peering from the VPC, then set ipv4_enabled = false and private_network on the instance, with a dependency on the peering.

How do I size GKE clusters per tenant without forking code?

Read a size class from configuration and map it to node limits in a locals lookup; drive everything else from JSON keys.

Why dispatch a separate workflow for admission control?

The policy controller is installed into the cluster after it exists, and doing it from the same root couples provider lifecycles; a dispatched workflow is re-runnable alone.

How should secondary projects access the main project?

Through cross-project IAM role bindings on service accounts, never through exported keys.

// The outcome

Two project types per folder and a repeatable tenant shape across lower and upper.

// Where to take it next

// Keep reading