Learn Terraform on Google Cloud by building real infrastructure, one resource at a time, ending with a GPU-backed LLM platform on GKE.
Problem: Clicking through the Cloud Console or pasting
gcloudcommands works once. Then nobody remembers which flags built prod, staging has quietly drifted away from it, and rebuilding after a mistake takes a week of archaeology.Solution: Terraform lets you declare your infrastructure in code, shows you a diff (
plan) before it changes anything, and records what it manages in state, so every environment is reviewable, repeatable, and disposable.
Many Terraform tutorials stop at "create one VM". This one keeps going to the infrastructure that DevOps and AI-infra engineers actually run: IAM done right, private networking, remote state, modules, CI/CD without keys, and GKE with GPU node pools serving a model.
Every concept comes with a runnable example under examples/. They all build toward one concrete outcome: an LLM inference platform on GKE: a custom VPC, a GKE cluster, a Spot GPU node pool that scales to zero, a GCS bucket for model weights, Workload Identity, and vLLM serving a small open model. Then you tear it all down and confirm the bill stops.
No prior Terraform experience assumed. If you're new to Terraform, read top to bottom. If you already know the basics, jump to the Table of Contents. Kubernetes basics help in Part 6; see the companion k8s-tutorial.
What you'll have built by the capstone:
---
config:
look: handDrawn
theme: default
themeVariables:
fontFamily: '"Comic Sans MS", "Comic Sans", "Segoe Print", "Bradley Hand", cursive'
clusterBkg: '#FAFAFA'
clusterBorder: '#94A3B8'
lineColor: '#64748B'
edgeLabelBackground: '#475569'
themeCSS: |
.edgeLabel, .edgeLabel p, .edgeLabel span { color: #FFFFFF !important; }
---
flowchart TB
you(["👩💻 you / CI<br/>terraform plan · apply"])
state[("🗄️ GCS bucket<br/>remote state + lock")]
subgraph project["☁️ Your GCP project"]
direction TB
subgraph vpc["🌐 Private VPC"]
direction TB
subgraph gke["☸️ GKE cluster"]
direction LR
sys["⚙️ system pool<br/>CPU nodes"]
gpu["🎮 GPU pool<br/>L4 · Spot · scale-to-zero"]
vllm["🤖 vLLM Pod<br/>serves the model"]
gpu --> vllm
end
end
models[("📦 GCS bucket<br/>model weights")]
ar[("🐳 Artifact Registry<br/>images")]
iam["🔐 IAM<br/>service accounts"]
end
you ==>|"desired state"| project
you <-->|"read / write"| state
vllm -. "Workload Identity<br/>no keys" .-> models
vllm -. pulls image .-> ar
iam -. least privilege .-> vllm
classDef ctrl fill:#0F172A,stroke:#2563EB,stroke-width:2px,color:#FFFFFF
classDef eng fill:#7B42BC,stroke:#4C1D95,stroke-width:3px,color:#FFFFFF
classDef tgt fill:#0F172A,stroke:#16A34A,stroke-width:2px,color:#FFFFFF
class you ctrl
class state eng
class sys,gpu,vllm,models,ar,iam tgt
style project fill:#1E293B,stroke:#334155,color:#F1F5F9,fillStyle:solid
style vpc fill:#000000,stroke:#94A3B8,color:#FFFFFF,fillStyle:solid
style gke fill:#000000,stroke:#94A3B8,color:#FFFFFF,fillStyle:solid
Every box above is a Terraform resource you write,
plan, and understand. There's no ClickOps step hiding underneath.
By the end you'll be able to:
- Explain the Terraform model: configuration, providers, the plan/apply loop, and why state exists.
- Write idiomatic HCL: variables, outputs,
for_each,lifecycle, and functions, without copy-paste. - Run state like a team: a GCS backend with locking, plus drift detection and refactoring with
moved,import, andremoved. - Build GCP foundations correctly: enabled APIs, least-privilege IAM (and the
_iam_policyvs._iam_membertrap), and secrets. - Provision core GCP services: a private VPC with Cloud NAT and tight firewall rules, buckets whose data gets cheaper as it ages, VMs with their own identity, and containers that scale to zero.
- Package and promote: write your own modules, consume registry modules, and separate dev from prod.
- Stand up AI infrastructure: GKE, GPU node pools with Spot and scale-to-zero, Workload Identity, and model storage.
- Ship it safely:
terraform test, linting, security scanning, and GitHub Actions that authenticate to GCP with no JSON keys. - Tie it all together in the capstone: an LLM inference platform you can build, use, and destroy on demand.
Every section is hands-on: you write some HCL, run terraform plan, read the diff, and apply it. Every curriculum chapter ends with a Checkpoint built around high-frequency decisions, small experiments, and common failure modes; answers stay collapsed until you choose to open them.
- A Linux, macOS, or WSL2 shell with basic command-line familiarity.
- Terraform 1.11+. Setup installs it. That's all Getting Started and Part 1 need: they run on your own machine.
- From Part 2 on, a Google Cloud account with billing enabled and the gcloud CLI. Free trial credit covers Parts 2–5, but free trial accounts can't use GPUs: Part 6 and the capstone need a paid account (your remaining credit carries over) and GPU quota. Connecting to GCP walks you through all of it.
💸 About cost. Getting Started and Part 1 cost nothing: they only create local files. Parts 2–5 use resources that are free or cost cents (GCS buckets, VPCs, service accounts, firewall rules). Part 6 and the capstone run GKE and GPUs, which bill by the hour. Every chapter ends with a cleanup step, Part 2 starts by having you create a budget alert before any cloud resource, and the Cost Guide lists what each part costs. Use a dedicated sandbox project so that deleting the whole project is always your last-resort cleanup.
📋 About the output shown. Plans, errors, and test results in the docs come from real runs of Terraform 1.16 and google provider 8.7, against a sandbox project ID or local mock APIs, and of Terraform 1.17 for the local-only chapters. Your project ID, project number, emails, lock IDs, and timestamps will differ; a few outputs that depend on running cloud resources (such as
kubectl get nodes) are illustrative and say so where it matters.
Before starting, check that Terraform works:
terraform version # Terraform v1.11 or newerIf it doesn't, follow Setup. The GCP setup comes later, in Connecting to GCP.
Getting Started
- What is Terraform?: Infrastructure as Code, and the one idea behind everything.
- Setup: install Terraform; nothing else is needed until Part 2.
- Core Workflow:
init→plan→apply→destroyon local resources, no cloud account needed. - Anatomy of HCL: blocks, arguments, and expressions.
Part 1 — Core Language
- Providers & Version Pinning: what a provider is, version constraints, and the lock file.
- Resources & Data Sources: manage vs. read.
- Variables, Locals & Outputs: inputs, computed values, and results.
- Expressions & Functions:
for, conditionals, andterraform console. - Meta-Arguments:
count,for_each,depends_on,lifecycle,-replace, and provisioners.
Part 2 — GCP & State
- Connecting to GCP: credentials, roles, a sandbox project with a budget alert, and your first bucket.
- State & Drift: what state is and how to inspect it.
- Remote Backend on GCS: shared state with locking.
- Refactoring: moved, import, removed: change addresses without destroying anything.
Part 3 — GCP Foundations
- Projects & APIs: enabling services and labeling everything.
- IAM & Service Accounts: least privilege, and the authoritative-binding trap.
- Secret Manager & Sensitive Values: secrets, and why state is sensitive.
Part 4 — GCP Services
- Networking: VPC, secondary ranges, Cloud NAT, and firewall rules.
- Cloud Storage: locations, storage classes, lifecycle rules, and
gcloud storage. - Compute Engine: a web server VM with a service account, a startup script, and IAP SSH.
- Cloud Run: a public container service that scales to zero, and its revisions.
- Cloud Functions: deploy source code, redeploy on change, and run on file uploads.
- BigQuery: datasets, tables, and views as code, and the schema change that deletes rows.
Part 5 — Modules & Environments
- Writing Modules: reusable units with a clean interface.
- Using Registry Modules:
terraform-google-modules, pinned and understood. - Environments: dev and prod without copy-paste drift.
Part 6 — Kubernetes & AI Infra on GCP
- GKE Cluster: Autopilot vs. Standard, private clusters, and release channels.
- GPU Node Pools: taints, drivers, Spot, scale-to-zero, and quotas.
- Workload Identity Federation for GKE: Pods that reach GCP with no keys.
- Model Storage & Artifact Registry: where weights and images live.
- Kubernetes & Helm Providers: deploy onto GKE, and the two-stage apply problem.
Part 7 — Team Workflow
- Testing & Code Quality:
fmt,validate, tflint, andterraform test. - Security Scanning: Trivy and Checkov before apply.
- CI/CD with GitHub Actions: keyless auth, plan on PR, apply on merge.
Capstone
- LLM Inference Platform on GKE: everything above, end to end.
- Cleanup: tear it down and confirm the bill stops.
Appendix
- Terraform Cheat Sheet: one-page reference.
- Troubleshooting: symptom → cause → fix.
- GCP Cost Guide: what costs money, and how to keep it near zero.
- Further Reading: advanced topics beyond this guide.
Every example is checked on each push by .github/workflows/ci.yml, with no cloud credentials: terraform fmt, init -backend=false and validate for every configuration and module, terraform test for the modules with tests, tflint with the google ruleset, actionlint for the workflows, and a link check for the docs. Renovate keeps provider, module, chart, action, and vLLM versions current. To run the same checks locally:
terraform fmt -check -recursive examples
tflint --init && tflint --recursive --config "$PWD/.tflint.hcl" --chdir=examples
python3 scripts/check-links.py README.md docs/*/*.md