// Why this matters
A private GKE cluster with Terraform is the baseline for any self-hosted collaboration tool that holds company conversations. Chat history is exactly the kind of data you do not want on nodes with public addresses, and a managed SaaS is sometimes ruled out by data residency or contract. Self-hosting is only sensible if the platform underneath is locked down and rebuilds from code.
The second reason is operability. Stateful apps on Kubernetes are painful when you wire the database, object storage and application together by hand. Operators encode the day-two knowledge (backups, rolling upgrades, replica sizing) so you declare intent in YAML and let controllers do the rest.
This is the shape I delivered for a freelance engagement: a hardened GKE foundation as reusable modules, then a handful of operator manifests on top. Everything below is generic and uses placeholder ranges and names.
// The problem
A default GKE cluster has nodes with external addresses, a public API endpoint open to the world, legacy basic authentication in older versions, and a default node pool you did not choose. Each of those is a finding in a security review. Fixing them after the fact usually means recreating the cluster.
Private nodes create their own problem: they cannot reach the internet to pull images from public registries or call external APIs. You need an egress path (Cloud NAT) and, for a predictable allowlist at the other end, reserved NAT addresses. You also need secondary IP ranges for pods and services chosen up front, because they are painful to change later.
Node pools bring the third trap. Changing machine type or disk on a Terraform-managed node pool forces replacement, and a naive destroy-then-create drains the pool while workloads have nowhere to go. Without a naming strategy you get downtime on what looks like a trivial change.
// The solution
The solution is three modules with narrow responsibilities. The VPC module creates a custom-mode network, one subnetwork with named secondary ranges for pods and services, private Google access, and optionally a router with NAT. The cluster module creates the control plane with private nodes, an authorised-networks list, network policy, vertical pod autoscaling and workload identity as an option, then deletes the default pool. The node pool module creates the real pool with a random suffix in its name.
The random suffix is the key trick. A random_id with keepers set to the immutable inputs (machine type, disk, labels, tags) produces a new suffix whenever any of those change, which changes the pool name, which makes Terraform create the new pool first (with create_before_destroy) and only then remove the old one. GKE cordons and drains the old nodes after the new ones are ready.
On top of the platform, operators own the stateful dependencies. A MySQL operator provisions the database, a MinIO operator provides S3-compatible file storage, and the chat operator watches a single installation resource with a size field such as the expected user count. I considered Helm charts for each component and rejected them because upgrade and backup behaviour then lives in your pipeline instead of in a controller. The trade-off is that you depend on the operators staying maintained; pin versions and check their release cadence before committing.
If you later need richer traffic policy between namespaces, a mesh is the next layer, but start with network policy and an ingress controller; they cover most needs with far less to operate. For the multi-project foundation this sits on, see The GCP Project Factory: Folder, Project, VPC and GKE per Tenant, and for a different take on GKE delivery see GKE Platform with Concourse CI, Vault and Pub/Sub.
- Network moduleVPC, subnetwork, secondary ranges, router, NAT
- Cluster moduleprivate nodes, no basic auth, network policy, VPA
- Node pool moduleseparate pool with random suffix for safe replacement
- Operatorsdatabase, object store and application operators
- IngressNGINX ingress controller
- App resource gateinstallation custom resource sized by user count
- VPC modulenetwork, ranges, NAT
- Cluster moduleprivate control plane, no default pool
- Node pool modulesuffix keyed on immutable inputs
- Access gateauthorised networks plus cluster-admin binding
- Operatorsdatabase, object store, app
- Ingresscontroller and TLS
- Installation CRsize by users
// Before you start
- A GCP project with billing, plus the Compute, Kubernetes Engine and Service Networking APIs enabled.
- Terraform 1.5+ with the google and google-beta providers, and a remote state bucket.
gcloud,kubectland Helm 3 installed; a user or service account with Kubernetes Engine Admin and Compute Network Admin.- A decision on three non-overlapping ranges: nodes, pods and services (for example /20, /16 and /20), and a /28 for the control plane peering.
- A DNS name you control for the ingress and a way to issue a TLS certificate.
// Step-by-step implementation
01 Module layout and pinned providers
Keep each concern in its own module directory and pass versions and ranges in as variables, never as literals inside the module. That is what makes the same code reusable for a second environment.
Pin provider versions in a root
versions.tf. The beta provider is only needed for features that have not reached GA in the main provider, so keep that boundary explicit.02 The VPC module: ranges, private Google access and Cloud NAT
Create the network with
auto_create_subnetworks = falseand a routing mode of GLOBAL. The subnetwork carries two named secondary ranges; GKE refers to them by name, so export the names as outputs and feed them to the cluster module.Cloud NAT is optional by variable. With
MANUAL_ONLYallocation you reserve static addresses and hand them to the NAT, which gives whoever sits at the other end of your outbound calls a stable allowlist. WithAUTO_ONLYGoogle picks the addresses. Always set minimum ports per VM high enough for your pod density, or outbound connections start failing under load.03 The cluster module: private nodes, authorised networks, no default pool
The cluster is regional, so the control plane is replicated across zones.
remove_default_node_poolwithinitial_node_count = 1is the idiom for creating the cluster without keeping the pool GKE insists on creating first.Private nodes mean workloads get no external addresses. The private endpoint flag decides whether the control plane is reachable from the internet at all; keeping it public but restricted with authorised networks is a good middle ground when your operators work from a known office or VPN range. Network policy is switched on here but does nothing until you apply policies in a later step.
04 The node pool module: a random suffix for safe replacement
Everything that forces node pool replacement goes into the
keepersmap of arandom_id. When any of those inputs changes, the suffix changes, the name changes, and withcreate_before_destroyTerraform builds the new pool first. Be careful when adding a keeper later: it triggers a one-off replacement for every consumer of the module.Set autoscaling bounds, auto-repair and auto-upgrade in the pool, and request only the OAuth scopes you need. Prefer workload identity to broad scopes where your apps call Google APIs.
05 Wire the modules together and apply
The root module only connects outputs to inputs. Keep the authorised networks list explicit and small; an empty list with a public endpoint is the same as no protection.
06 Install the database, object-store and chat operators
Create one namespace per operator and apply the operator manifests, pinned to a release rather than a moving branch. Wait for each deployment to become available before the next step; the application operator expects the other two CRDs to exist.
Download the manifests from the operator project release page for the version you choose and keep them in your repo, so an upstream change cannot alter your platform without a review.
07 Ingress controller, then the installation resource sized by users
Install the NGINX ingress controller with Helm; on GKE it provisions a regional load balancer and gives you one address to point DNS at. The chat application is then a single custom resource. Its size field maps to replica counts and resource requests inside the operator, and the database and file storage sizes become persistent volume claims.
Treat the size as a starting point and revisit it with real concurrency numbers; an operator profile for fifty users is not a performance guarantee.
08 Lock down the namespace with a default-deny network policy
Because the cluster has network policy enforcement on, a default-deny policy now actually blocks traffic. Add one to the application namespace, then allow only what is required: ingress from the controller namespace, DNS, and the database and object store inside the namespace.
// How to verify it works
kubectl get nodes -o wideshows only internal addresses;gcloud compute instances listshows no external IPs on the nodes.- From a pod,
curl -s https://example.com -o /dev/null -w "%{http_code}"succeeds through NAT; the NAT logs show the translation. - Change the node machine type in Terraform and run plan: it shows the pool replaced with a new suffix and
create_before_destroy, not an in-place edit. kubectl -n chat get clusterinstallationreports Stable, and the pods for database, object store and app are Ready.- A pod in another namespace cannot reach the chat database port, confirming the default-deny policy works.
// Design decisions and trade-offs
- Private nodes with NAT for egress; default node pool removed.
- Operators own the stateful dependencies.
- Modules take versions and ranges as variables.
// Pitfalls and lessons learned
- Pod and service ranges are hard to change later. Size them for growth: a /14 for pods is generous but cheap, and a /20 for services rarely runs out.
- A public control plane with an empty authorised-networks list is open to the internet. Always populate it, or switch to a private endpoint and use a bastion or VPN.
- Adding a key to the node pool
keepersmap triggers replacement of every existing pool using the module. Plan a maintenance window. - Cloud NAT with too few ports per VM causes intermittent outbound connection failures that look like application timeouts.
- Network policy objects are accepted silently when the cluster does not enforce them. Confirm enforcement is on before you rely on a policy.
- Operator manifests pulled from a moving branch can change under you. Pin a release and commit the YAML.
// Frequently asked questions
How do I create a private GKE cluster with Terraform?
Set private_cluster_config with enable_private_nodes = true and a /28 master_ipv4_cidr_block, give the subnetwork secondary ranges for pods and services, restrict the control plane with master_authorized_networks_config, and add Cloud NAT so nodes can pull images.
Why remove the default node pool?
The default pool is created with settings you did not choose and is awkward to manage. Creating the cluster with remove_default_node_pool and then defining a separate pool lets Terraform own every setting.
Why use a random suffix in the node pool name?
Many node pool settings force replacement. A suffix derived from those settings changes when they do, so Terraform builds the new pool before deleting the old one, avoiding a window with no nodes.
Operators or Helm charts for databases and storage?
Operators encode backup, scaling and upgrade logic and reconcile continuously. Helm is simpler but leaves day-two behaviour to you. Choose operators when the project is actively maintained; otherwise prefer a managed database service.
Do I need a service mesh?
Not to start. Network policy and an ingress controller cover isolation and TLS termination. Add a mesh when you need mutual TLS between services or fine-grained traffic shifting.
// The outcome
A hardened, repeatable base for stateful self-hosted apps.
// Where to take it next
- Add backups for the database and object store, and rehearse a restore into a scratch namespace.
- Replace the node-wide scopes with workload identity bindings per service account.
- Move TLS to cert-manager with an ACME issuer so certificates renew themselves.
- Provision the surrounding project and networking with The GCP Project Factory: Folder, Project, VPC and GKE per Tenant so this module set drops into a repeatable foundation.