Hour 7: Infrastructure as code and automation
About this hour
Hours 1 to 6 described what a landing zone contains: a resource hierarchy, identity, guardrails, a network hub, hybrid connectivity, logging and cost control. This hour shows how to build all of it as code, so that it is repeatable, reviewable and recoverable. The tool is Terraform with the Google provider, the state lives in a Cloud Storage bucket, and the changes travel through pull requests and a pipeline instead of console clicks.
The hour follows the order in which a real team builds automation. You start with the idea of state and plan (Module 1), create the protected bucket where state lives (Module 2), pin providers and modules so that runs are reproducible (Module 3), and automate project creation with labels, budgets, APIs and Shared VPC attachment (Module 4). Then you connect it to a pipeline with keyless authentication (Module 5), detect drift and stop bad plans (Module 6), do a hands-on lab (Module 7) and learn to troubleshoot the typical failures (Module 8).
The examples are written for a sandbox. Every lab says what it creates, what it costs and how to remove it. Where an organization is not available, the labs fall back to a single sandbox project, and each module says which part you cannot practise without one.
What you will be able to do
- Explain what Terraform state, plan and apply do, and why a landing zone is split into layers with separate state and separate service accounts.
- Create a protected state bucket with
gcloud storage, configure the GCS backend and migrate local state withterraform init -migrate-state. - Pin Terraform, provider and module versions, and run
fmt,validateand a savedplan -outas a quality gate. - Write a project factory module that sets the parent, billing, labels, enabled APIs, budget, Shared VPC attachment and deletion protection, and review its plan.
- Design a pipeline that plans on pull request and applies after approval, using Workload Identity Federation and one service account per layer.
- Detect drift with scheduled plans, import existing resources and apply policy checks to plan output.
- Diagnose the usual failures: state lock, API not enabled, provider upgrade, missing roles for the CI identity, console drift and HTTP 403.
Schedule (60 minutes)
| # | Module | Window | Minutes |
|---|---|---|---|
| 1 | Why Terraform for the landing zone | 00–06 | 6 |
| 2 | Bootstrap: the state bucket | 06–13 | 7 |
| 3 | Providers and modules | 13–20 | 7 |
| 4 | Project factory | 20–28 | 8 |
| 5 | CI/CD for infrastructure | 28–36 | 8 |
| 6 | Drift, policy checks and reviews | 36–43 | 7 |
| 7 | Lab: Terraform in a sandbox | 43–53 | 10 |
| 8 | Troubleshooting IaC | 53–60 | 7 |
| Total | 60 |
The minutes include reading, the animation, the quiz and the short exercises in each module. The labs in Modules 2, 3 and 4 take about 15 minutes each if you run them, and they are worth doing in your own sandbox. Module 7 is the consolidating lab. Treat these as study time that can be spread over several sittings.
What the labs create, and what they cost
| Module | What the lab creates | Needs an organization? | Cost |
|---|---|---|---|
| 1 | Nothing in Google Cloud: a local configuration with one data source, to practise init, plan, apply and state | No | Free |
| 2 | A state bucket with versioning, and one demo bucket; local state migrated to the bucket | No | Low (usually well under a few USD per day for this lab) |
| 3 | A local module that creates one labelled bucket, from a saved plan | No | Low (usually well under a few USD per day for this lab) |
| 4 | A sandbox project with labels, one API, a budget and deletion protection | Optional (without one the project has no parent) | Free for project, API and budget |
| 7 | The consolidated lab: state bucket, small labelled configuration, plan, apply, state inspection, destroy | No | Low (usually well under a few USD per day for this lab) |
gcloud projects list and gcloud storage buckets list at the end of the session. Do not leave a state bucket and demo resources behind.A first look at the code
The whole hour is built on a small amount of HCL. A first taste, so the pieces are familiar before the modules go deep:
terraform {
required_version = ">= 1.5, < 2.0"
required_providers {
google = {
source = "hashicorp/google"
version = "~> 6.0"
}
}
backend "gcs" {
bucket = "PROJECT_ID-tfstate"
prefix = "terraform/projects"
}
}
resource "google_folder" "prod" {
display_name = "prod"
parent = "organizations/ORG_ID"
}
Four things happen in this snippet: the Terraform and provider versions are pinned, the state is stored in a Cloud Storage bucket with a prefix for this layer, and the desired state declares a folder. Running terraform plan compares this with the real world and shows the change; terraform apply makes it.
What you need
- A Google Cloud sandbox project with billing linked and a budget alert already in place. Hour 1 shows how to set it up.
- Cloud Shell, or a workstation with Terraform 1.x and the gcloud CLI. The Setup page lists the check commands.
- For the organization-level examples (folders, Organization Policy, Shared VPC attachment): a sandbox organization or a sandbox folder in which you hold the roles named in the Setup page. Without an organization you can still do every lab with a single project.
- Basic comfort with a terminal and Git. You do not need to know HCL beforehand; the modules introduce each construct.
How to study this hour
- Read the Concepts tab of a module, then look at the diagrams and run the animation.
- Run the Commands tab in a sandbox, in order. Expected output is shown, and IDs in it are illustrative.
- Do the Lab tab and run the verification after each step. Do the cleanup, even if the lab seems small.
- Answer the quiz at the end of the module. The explanations say why the right answer is right.
- Use the Troubleshooting tab as a reference. Module 8 collects the failures you will meet most often in real projects.
bootstrap, org, networks, projects) and commit after each lab. At the end you have a small, working skeleton of a real landing-zone repository.Setup
Choose where to work
| Option | Good for | Notes |
|---|---|---|
| Cloud Shell | Fastest start; nothing to install | Terraform and gcloud are pre-installed and you are signed in. The home directory persists between sessions, but the shell VM is temporary. Do not keep long-lived secrets there. |
| Workstation | Daily work, editors, Git, longer sessions | Install Terraform 1.x and the gcloud CLI (current release channel). Authenticate with gcloud auth login and gcloud auth application-default login. |
| Dev container or CI image | Teams that want identical tool versions | Pin the Terraform version in the image so laptops and the pipeline behave the same. |
Tools and versions
- Terraform 1.x with the Google provider. Pin the major version in
required_providers(for exampleversion = "~> 6.0"). This course does not depend on one exact version; check the current Terraform and provider release notes before production use. - gcloud CLI (current release channel). Use
gcloud components updateif you installed it from the standalone package, or your package manager. - Git, for the pull-request flow in Modules 5 and 6.
- Optional:
jqto read JSON plans, and an editor with HCL support.
Check commands
Run these first. Expected output is illustrative.
terraform version gcloud version gcloud auth list gcloud config list project
Terraform v1.x.y on linux_amd64 Google Cloud SDK 5xx.x.x Credentialed Accounts ACTIVE ACCOUNT * you@example.com [core] project = PROJECT_ID
If terraform is not found, install it from the HashiCorp download page (see the Sources page). If gcloud config list project shows no project, set one with gcloud config set project PROJECT_ID.
Authentication for Terraform
The Google provider uses Application Default Credentials (ADC). On a workstation, create them once:
gcloud auth application-default login gcloud auth application-default print-access-token > /dev/null && echo "ADC ok"
In Cloud Shell, ADC come from the signed-in user automatically. For a service account, prefer impersonation to a key file:
gcloud auth application-default login --impersonate-service-account=SA_EMAIL
Your user then needs roles/iam.serviceAccountTokenCreator on that service account. Never create or download service account key files for this course. In pipelines, Module 5 uses Workload Identity Federation instead.
The sandbox project
Use a project that is dedicated to this hour, so that you can delete it afterwards. It holds the state bucket of the labs.
- Create or choose the project (
PROJECT_ID) and link a billing account. Hour 1 coversgcloud projects createandgcloud billing projects link PROJECT_ID --billing-account=BILLING_ACCOUNT_ID. - Set a budget on the project or billing account before you create anything. Budgets send alerts; they do not stop spending.
- Enable the APIs used in this hour:
gcloud services enable storage.googleapis.com cloudresourcemanager.googleapis.com serviceusage.googleapis.com iam.googleapis.com cloudbilling.googleapis.com --project=PROJECT_ID
Enabling APIs is free. Module 4 addsbillingbudgets.googleapis.comin the quota project for the budget example. - Verify:
gcloud services list --enabled --project=PROJECT_ID --format="value(config.name)" | grep -E "storage|cloudresourcemanager|serviceusage"
Roles you need
| Lab | Where | Roles (or equivalent permissions) |
|---|---|---|
| Modules 1 to 3 | Sandbox project | roles/storage.admin (create and manage buckets), roles/viewer (read the project); the sandbox project owner has these |
| Module 4: create a project | Sandbox folder (or no parent) | roles/resourcemanager.projectCreator on the folder, roles/billing.user on BILLING_ACCOUNT_ID; for budgets, a billing role that can create budgets such as roles/billing.costsManager (check the current role list) |
| Module 4: Shared VPC attachment (optional) | Organization or folder | roles/compute.xpnAdmin; needs an organization and a host project from Hour 4 |
| Module 5: pipeline identity (read and design) | Project and service accounts | roles/iam.workloadIdentityPoolAdmin, roles/iam.serviceAccountAdmin in a sandbox only |
| Module 7: consolidating lab | Sandbox project | Same as modules 1 to 3 |
Use groups for people (GROUP_EMAIL) and avoid roles/owner and roles/editor outside a throwaway sandbox. In production the pipeline service accounts hold these roles, not people.
What to do without an organization
A personal account or a project without a parent has no organization. You can still do the labs:
- Folders, Organization Policy, organization log sinks and Shared VPC (host and service project) need an organization. Skip the folder arguments and read these parts as design; the HCL is the same, only the parent changes.
- Module 4: leave
folder_idasnullto create a project without a parent. You need permission to create projects and a billing account you may link. - For a free organization to practise on, consider a Cloud Identity Free tenant with a verified domain that you own (Hour 1, Module 4). Use it only for training, and keep break-glass access protected.
Repository layout for this hour
landing-zone/
bootstrap/ # seed project, state bucket, pipeline service accounts
org/ # organization policies, shared projects, log sinks
networks/ # host projects, Shared VPC, firewall policy, NAT
projects/ # project factory and its data file
modules/
project/ # one purpose per module
labelled_bucket/
.github/workflows/ # or cloudbuild/ for Cloud Build
.gitignore # *.tfstate, *.tfplan, .terraform/, *.tfvars with secrets
cat > .gitignore <<'EOF' .terraform/ *.tfstate *.tfstate.* *.tfplan tfplan crash.log *.auto.tfvars.secret EOF
Commit .terraform.lock.hcl. Do not commit state, plan files or any file that holds a secret.
Budget and cleanup
- Expect free to low cost: the resources in the labs are small and short-lived. Budgets send alerts and do not cap spend.
- At the end of each lab run its cleanup, then check
gcloud storage buckets list --project=PROJECT_IDandgcloud projects list. - When the whole hour is done, delete the sandbox project (
gcloud projects delete PROJECT_ID); it stays recoverable for the pending-deletion period withgcloud projects undelete PROJECT_ID.
Module 1 · Why Terraform for the landing zone
- Explain why a landing zone is built from code and state instead of console clicks and shell scripts.
- Describe the Terraform workflow (write, init, plan, apply) and what the state file records.
- Map the landing-zone layers (bootstrap, organization, environments, networks, projects) to separate Terraform configurations with separate state.
The short answer
Infrastructure as code (基础设施即代码) means that the landing zone is described in text, stored in Git, reviewed in pull requests and created by a tool. Terraform is the most widely used tool for this on Google Cloud, because it has a mature Google provider, a clear plan-before-change workflow, a remote state with locking, and a large library of tested modules. Hours 1 to 6 showed what a landing zone contains. This hour shows how to build and change it safely, repeatably and with an audit trail.
What: the four ideas you need
- Configuration.
.tffiles written in HCL. They declare the desired state: "this folder exists, with this display name, under this parent". You do not write the steps. - Provider. A plugin that talks to one API. The
hashicorp/googleprovider calls the Google Cloud APIs. Thehashicorp/google-betaprovider exposes features that are not yet GA. - State (状态). A JSON record that maps each resource address in the code (for example
google_folder.prod) to the real object (folders/555555555555) plus its last known attributes. It is how Terraform knows what it already manages. - Plan and apply.
terraform plancompares configuration, state and the refreshed real resources and prints the differences.terraform applyperforms them, then writes the new state.
Why: console clicks and scripts do not scale
- Repeatability. The tenth project must look like the first. A module guarantees that labels, APIs, billing link and network attachment are identical every time.
- Review. A pull request shows who asked for the change, who approved it and what the plan said. The console keeps an audit log of what was done, but not why, and not before it happened.
- Drift detection. Because state records what Terraform created, a scheduled plan can tell you that somebody changed something by hand (Module 6).
- Recovery. If a folder tree or a project is damaged, the code is the recipe to rebuild it. State and Git history tell you what existed.
- Least privilege for people. When automation makes the changes, engineers do not need standing Organization Administrator rights. The pipeline identity has them, with strict controls around it (Module 5).
How it works internally
terraform initdownloads providers and modules into.terraform/, writes the dependency lock file.terraform.lock.hcland configures the backend where state lives.terraform planbuilds a dependency graph of all resources, acquires the state lock, reads the state, calls each provider to refresh the real objects, and computes the difference between the refreshed objects and the configuration.terraform applywalks the graph, creating independent resources in parallel and dependent ones in order. Each success is written to the state. A failure in the middle leaves a state that records what did succeed, which is why the state must never be edited by hand.- The next plan starts from the new state. If the plan is empty, the real world matches the code.
The landing zone as layers
The Google Cloud enterprise foundations blueprint (and its Terraform example repository) splits the landing zone into stages. Each stage is a separate Terraform configuration with its own state and, in a mature setup, its own service account. The exact names vary between versions of the blueprint, so treat this table as the pattern and check the current repository for the details.
| Layer | What it creates | Who runs it | Typical state prefix |
|---|---|---|---|
| Bootstrap | Seed project, state bucket, automation service accounts, CI/CD project, the first folders if needed | A person with organization-level rights, once, then rarely | Local first, then gcs bucket in the seed project |
| Organization | Organization Policies, organization IAM bindings, log sinks, shared projects (logging, billing export, security) | Organization pipeline service account | terraform/org |
| Environments | Folders for prod, nonprod, dev, their policies, per-environment KMS and secrets projects | Environment pipeline service account | terraform/envs |
| Networks | Host projects, Shared VPC, subnets, firewall policies, Cloud NAT, DNS, hybrid connectivity | Network pipeline service account | terraform/networks |
| Projects | The project factory: service projects with labels, budgets, enabled APIs and Shared VPC attachment | Project pipeline service account | terraform/projects/TEAM |
| Applications | Workload resources inside the projects the factory created | Application teams through their own pipelines | One state per application |
When to use Terraform, and when something else
| Option | Strength | Weakness for a landing zone |
|---|---|---|
| Console | Fast to explore, good for learning | No review, no repeatability, no plan, easy to drift |
| gcloud scripts | Direct, no state, good for one-off tasks and checks | Imperative: re-running may fail or duplicate; no diff; no drift detection |
| Terraform (or OpenTofu) | Declarative, plan before change, state, modules, wide provider support | State must be protected; learning curve; provider lag on new features |
| Infrastructure Manager | Google-managed service that runs Terraform and keeps state for you | Fewer integrations than a CI system you control; check current capabilities |
| Config Connector / KRM | Manages Google Cloud resources as Kubernetes objects | Needs a cluster; the landing zone should not depend on a workload cluster |
| Deployment Manager | Older Google-native templates | Google has announced its retirement; do not start new work with it (check the current status) |
Mental model
Think of three things that must agree: code (what you want), state (what Terraform believes it built) and reality (what Google Cloud has). Plan compares them. If code and reality differ, the plan proposes changes. If state and reality differ (someone deleted a resource), the plan notices during refresh. If you want a resource under management that already exists, you import it into the state.
Figure 1. Landing-zone layers. Lower layers are created first; each has a separate state and a separate identity, so a mistake in one layer cannot rewrite another.
Figure 2. Plan compares three things. Look at the box in the middle: nothing is changed until the diff is reviewed and applied.
In Figure 1 look at the order of the arrows: bootstrap feeds everything, networks and the project factory depend on the environments, and applications depend on projects. In Figure 2 look at the three sources feeding the plan: a change in any one of them shows up as a difference.
The animation follows one change, adding a folder, through the Terraform workflow: pull request, plan, state lock, refresh, apply and state write. Watch where the lock is taken and released, because that is what prevents two runs from changing the same layer at once.
These commands are the basic loop. Run them in Cloud Shell or on a workstation with Terraform 1.x and the gcloud CLI. Read-only commands come first. Terraform itself is free; any Google Cloud resource it creates is billed, and each write command below says so.
terraform version
Purpose. Shows the Terraform version and the provider versions recorded for the current directory. Run it first to confirm that you are on a 1.x release.
terraform version
Terraform v1.x.y on linux_amd64 + provider registry.terraform.io/hashicorp/google v6.x.y
Flags. -json prints machine-readable output for scripts. Common errors. command not found means Terraform is not installed or not on the PATH. Cloud Shell has Terraform pre-installed. Production use. Pipelines pin the Terraform version (for example in a container image) so a laptop and the pipeline behave the same.
gcloud auth application-default login
Purpose. Creates Application Default Credentials (ADC) that the Google provider uses on a workstation. It costs nothing. In production the credentials come from service account impersonation or Workload Identity Federation, never from a key file.
gcloud auth application-default login --impersonate-service-account=SA_EMAIL
Credentials saved to file: [/home/user/.config/gcloud/application_default_credentials.json] These credentials will be used by any library that requests Application Default Credentials (ADC).
Flags. --impersonate-service-account makes the credentials act as that service account, so your user needs roles/iam.serviceAccountTokenCreator on it. Common errors. Permission 'iam.serviceAccounts.getAccessToken' denied means that role is missing. In Cloud Shell, ADC come from the logged-in user automatically. Check gcloud auth application-default login --help for the flags in your SDK version.
terraform init
Purpose. Downloads providers and modules, writes .terraform.lock.hcl and initialises the backend. It does not change any cloud resource and is free.
terraform init
Initializing the backend... Initializing provider plugins... - Finding hashicorp/google versions matching "~> 6.0"... - Installing hashicorp/google v6.x.y... Terraform has been successfully initialized!
Flags. -upgrade moves providers to the newest version allowed by the constraints. -backend-config=KEY=VALUE supplies backend settings at run time. -migrate-state and -reconfigure are covered in Module 2. Common errors. Failed to query available provider packages usually means that the network blocks registry.terraform.io. Production use. Commit .terraform.lock.hcl so everyone and the pipeline install the same provider build.
terraform plan -out=tfplan
Purpose. Computes the changes and saves the plan to a file. Planning reads the real resources and is free, though it can make many API calls.
terraform plan -out=tfplan
Terraform will perform the following actions:
# google_folder.prod will be created
+ resource "google_folder" "prod" {
+ display_name = "prod"
+ id = (known after apply)
+ parent = "organizations/123456789012"
}
Plan: 1 to add, 0 to change, 0 to destroy.
Saved the plan to: tfplan
Flags. -var 'name=value' and -var-file=FILE set variables. -target limits the plan to one resource; use it only for recovery, never as a routine habit. -detailed-exitcode returns 2 when there are changes (Module 6). Symbols. + create, ~ update in place, - destroy, -/+ destroy and recreate. Always read the -/+ and - lines first.
terraform apply tfplan (write)
Purpose. Applies exactly the saved plan. Cost depends on the resources in the plan: a folder or a project is free, a VM or NAT gateway is billed. Applying a saved plan needs no confirmation prompt, because the plan was already reviewed.
terraform apply tfplan
google_folder.prod: Creating... google_folder.prod: Creation complete after 3s [id=folders/555555555555] Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Common errors. Saved plan is stale means the state changed after the plan was made; plan again. Error 403: The caller does not have permission means the identity lacks a role (Module 8). Production use. Pipelines always apply a saved plan artifact, never a fresh apply -auto-approve without a review.
terraform state list
Purpose. Lists every resource address in the state. It is read-only and free, and it is the fastest way to check what Terraform manages.
terraform state list
google_folder.prod google_project.app_a google_project_service.app_a["compute.googleapis.com"]
Makefile or pipeline definition so nobody types them from memory, and never run terraform state rm or state mv except in a reviewed change (Module 6).Lab 1: a first Terraform run with no cost (about 12 minutes)
Goal. Run the whole Terraform loop (init, plan, apply, state, destroy) against a data source only, so that nothing is created in Google Cloud. You see the files, the state and the lock file, which prepares you for the bucket and project labs later in this hour.
Prerequisites. Cloud Shell, or a workstation with Terraform 1.x and the gcloud CLI, and a sandbox project you can read (roles/viewer is enough). IDs in the expected output are illustrative.
- Authenticate and set the project. In Cloud Shell the user is already signed in.
gcloud config set project PROJECT_ID gcloud auth application-default login # skip in Cloud Shell
- Create a working folder and a file
main.tf.mkdir -p ~/tf-first && cd ~/tf-first cat > main.tf <<'EOF' terraform { required_version = ">= 1.5" required_providers { google = { source = "hashicorp/google" version = "~> 6.0" } } } provider "google" { project = var.project_id } variable "project_id" { type = string description = "Sandbox project to read." } data "google_project" "this" {} output "project_number" { value = data.google_project.this.number } output "parent" { value = data.google_project.this.org_id != null ? "organizations/${data.google_project.this.org_id}" : "no organization" } EOF - Initialise. Verify: the message
Terraform has been successfully initialized!appears and the files.terraform/and.terraform.lock.hclexist.terraform init ls -a
- Format and validate. Verify:
terraform fmtprints nothing (or the file names it fixed) andvalidateprintsSuccess! The configuration is valid.terraform fmt terraform validate
- Plan and apply. A data source creates nothing, so the plan has only outputs.
terraform plan -var="project_id=PROJECT_ID" -out=tfplan terraform apply tfplan
Changes to Outputs: + parent = "organizations/123456789012" + project_number = "987654321098" Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
- Inspect the state. Verify: the state file exists locally and lists the data source.
terraform state list terraform show | head -20 ls -l terraform.tfstate
data.google_project.this
- Break it on purpose to see the error format: change
project_idto a project that does not exist and runterraform plan. Expected: an error such asError 403orproject not found. Restore the correct ID.
Expected result. Terraform initialised, validated and applied with zero resources added, and you saw both the lock file and a local state file. Local state is fine for this read-only exercise. It is exactly what Module 2 replaces with a remote bucket.
Cost. Free. Only read API calls are made.
Cleanup. Nothing was created in Google Cloud. Remove the local folder: cd ~ && rm -rf ~/tf-first.
Lab 2 (optional): read a real blueprint
Open the Terraform example foundations repository on GitHub (listed on the Sources page) and write down: how many stages it has, what each stage creates, and which service account runs each stage. Compare it to the table in the Concepts tab.
Real cases
- The console landing zone that nobody could rebuild. A company built its folders, projects and firewall rules by hand over two years. When a regulator asked for evidence of how a production project was configured, the only source was memory and screenshots. They imported the existing objects into Terraform one layer at a time, starting with folders and Organization Policies, and the next audit used the plan output and Git history as evidence.
- One state for everything. A single configuration held the organization, networks and every project. Each change took thirty minutes to plan, any run needed Organization Administrator, and two engineers regularly blocked each other on the state lock. Splitting it into layers cut plan time, narrowed each service account and removed the lock contention.
- The deleted state bucket. A cleanup script deleted a bucket that looked unused. It was the state bucket of the networks layer. Object versioning and a bucket with deletion protection (Module 2) would have allowed recovery; the team recovered from an older copy and re-imported the differences, which took two days.
Practices
- One repository (or one directory per layer) with a clear owner for each layer; separate state prefix and service account per layer.
- Every change through a pull request that shows the plan; no routine
applyfrom a laptop. - Pin Terraform and provider versions, and commit the lock file.
- Write modules for patterns that repeat (project, subnet, sink), and keep them small, with documented inputs and outputs.
- Decide early who may run bootstrap again and under which approval, because it holds the most powerful identities.
roles/storage.objectAdmin on it to the pipeline identities, and never commit terraform.tfstate or *.tfvars with secrets to Git. Add them to .gitignore.Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
terraform: command not found | Terraform not installed or not on PATH | which terraform; in Cloud Shell use the pre-installed binary |
Error: Failed to query available provider packages | Network or proxy blocks the registry, or a bad version constraint | terraform init with a clean .terraform/; check the constraint in required_providers |
could not find default credentials | No Application Default Credentials | gcloud auth application-default print-access-token |
Error 403: The caller does not have permission | The identity lacks a role, or the API is disabled | gcloud auth list and the role list on the target project or folder |
| Plan wants to destroy and recreate a resource | A change to an argument that cannot be updated in place (-/+) | Read the # forces replacement comment next to the argument |
| Plan shows changes nobody made in code | Drift from a manual console change, or a provider default changed | Compare the plan with the audit log for that resource (Hour 6) |
Triage order
- Which identity is Terraform using?
gcloud auth listand, for impersonation, the provider block. - Which project and layer is the run for? Check the backend prefix and the
projectsetting. - Read the first error in the output, not the last; later errors are often consequences.
- Run
terraform validate, thenterraform planagain; setTF_LOG=INFOonly if the message is not enough, and never paste logs with tokens into tickets.
Video content changes quickly. These are search pages and official documents, not pinned video links. Check the date of a video against the Terraform and provider documentation you use.
- YouTube search: Terraform and Google Cloud landing zone foundation
- YouTube search: Terraform remote state explained
- YouTube search: Terraform plan and apply workflow
Official reading: Terraform on Google Cloud · What is Terraform · Security foundations guide · terraform-example-foundations.
Module 2 · Bootstrap: the state bucket
- Create a Cloud Storage bucket for Terraform state with uniform bucket-level access, public access prevention and object versioning.
- Write a GCS backend block and move existing local state into the bucket with
terraform init -migrate-state. - Explain how state locking, per-layer prefixes and least-privilege access protect the state.
The short answer
The state bucket (状态存储桶) is a Cloud Storage bucket that holds Terraform state. It is the first thing the bootstrap layer creates, because every other layer stores its state there. The design goals are simple: private, versioned, locked while in use, and reachable only by the identities that need it.
What: the pieces
- The bucket. A regional (or dual-region) bucket with a globally unique name, created in a protected seed project.
- Uniform bucket-level access. Disables object ACLs so that IAM is the only access control. This is also what Organization Policy
constraints/storage.uniformBucketLevelAccessenforces in Hour 3. - Public access prevention. Blocks any grant to
allUsersorallAuthenticatedUsers, even by mistake. - Object versioning (对象版本控制). Keeps non-current versions of the state object so you can go back.
- The GCS backend. A
backend "gcs"block withbucketandprefix. Terraform writesPREFIX/default.tfstatefor the default workspace and a lock object next to it while it runs.
Why: state is the most sensitive file you own
- It lists every resource you manage and their IDs, which is a map of your estate.
- It can contain secrets in plain text (initial passwords, keys created by Terraform, connection strings).
- Whoever can write the state can make Terraform believe something exists or does not, and the next apply will act on it.
- Losing it forces long, error-prone imports.
How it works internally
- You declare
backend "gcs" { bucket = "..." prefix = "..." }. Backend blocks cannot use variables, so bucket and prefix are literals, or you pass them with-backend-configat init time. terraform initsees the new backend. If a localterraform.tfstateexists,-migrate-stateasks whether to copy it to the bucket.- On every plan or apply, Terraform writes a lock object in the bucket, reads the state object, does its work, writes a new state object generation and removes the lock.
- Authentication uses Application Default Credentials, an access token, or impersonation (
impersonate_service_accountin the backend block). No key file is needed.
The bootstrap chicken-and-egg problem
The bucket must exist before the backend can use it, but you want the bucket itself to be managed by Terraform. The usual solution is two passes. In the first pass the bootstrap configuration runs with local state and creates the seed project and the bucket. In the second pass you add the backend "gcs" block and run terraform init -migrate-state, so the bootstrap's own state moves into the bucket it created. A small, safe alternative for a sandbox is to create the bucket with gcloud (this module's commands) and let Terraform manage everything else.
Design decisions
| Decision | Options | Recommendation |
|---|---|---|
| Where does the bucket live? | Seed project, or each application project | One protected seed project; never in a project that application teams administer |
| One bucket or many? | One with prefixes, or one per layer | One bucket is simpler; use one bucket per layer when you need strict separation by IAM |
| Location | Region, dual-region, multi-region | Region (or dual-region for higher resilience) that satisfies your residency rules (gcp.resourceLocations) |
| Encryption | Google-managed key or CMEK | Google-managed by default; CMEK if policy requires it (Hour 3) |
| Recovery | Versioning, soft delete, lifecycle rule | Versioning on, plus a lifecycle rule to delete non-current versions after a retention period |
| Access | Individuals, groups, service accounts | Pipeline service accounts and a small admin group; humans read through a break-glass group only |
When to use something else
| Option | When it fits | Why it is not the default here |
|---|---|---|
| Local state | First bootstrap run, throwaway labs | No locking, no sharing, lost with the laptop |
| GCS backend | Almost every Google Cloud team | Default: native locking, IAM, versioning, no extra service |
| HCP Terraform or another remote service | When you already run Terraform centrally | Adds a vendor and its own access model; valid, but outside this course |
| Infrastructure Manager | When Google should run Terraform and hold state | Different operating model; check current capabilities before choosing |
Figure 1. One bucket, one state object per layer, one service account per layer. Look at the lines: a layer's identity reaches only its own prefix; people are the exception, not the rule.
Figure 2. The two-pass bootstrap. The state moves into the bucket that it created, so the bucket is managed like everything else.
The animation shows the bootstrap sequence: create the bucket, enable versioning, add the backend block, migrate the state, authorise a pipeline identity and take a lock during the next plan. Each log line is the kind of message you will see in your own terminal.
These commands create and inspect the state bucket. Replace uppercase placeholders. Bucket names are globally unique, so a good pattern is PROJECT_ID-tfstate. Check gcloud storage buckets create --help for the flags in your SDK version.
gcloud storage buckets create (write)
Purpose. Creates the state bucket with the baseline protections in one command. The bucket is empty, so it costs almost nothing; storage is billed only for what you keep (low for state files).
gcloud storage buckets create gs://PROJECT_ID-tfstate \ --project=PROJECT_ID \ --location=REGION \ --uniform-bucket-level-access \ --public-access-prevention
Creating gs://PROJECT_ID-tfstate/...
Flags. --location sets the region, dual-region or multi-region (REGION such as europe-west1). --uniform-bucket-level-access turns off object ACLs. --public-access-prevention blocks public grants. Common errors. HTTPError 409: Your previous request to create the named bucket succeeded and you already own it or 409 bucket name not available means the name is taken; choose another. 403 ... storage.buckets.create means you lack roles/storage.admin (or a custom role with that permission) in the project. Production use. Bootstrap creates the bucket with Terraform and the same settings; the gcloud form is for sandboxes and for the very first manual step.
gcloud storage buckets update --versioning (write)
Purpose. Turns on object versioning, so each overwrite or delete keeps the previous generation. Non-current versions are billed as storage, so add a lifecycle rule to expire them later (low cost for state files).
gcloud storage buckets update gs://PROJECT_ID-tfstate --versioning
Updating gs://PROJECT_ID-tfstate/... Completed 1
Flags. --versioning enables it; --no-versioning disables it. Related flags in the same command set a lifecycle policy from a JSON file (--lifecycle-file) and soft-delete retention; check gcloud storage buckets update --help for the exact forms in your SDK version. Production use. A lifecycle rule that deletes non-current versions after 30 to 90 days, and keeps a minimum number of newer versions, balances recovery and cost.
gcloud storage buckets describe
Purpose. Verifies the settings. Read-only and free.
gcloud storage buckets describe gs://PROJECT_ID-tfstate \ --format="yaml(name,location,uniform_bucket_level_access,public_access_prevention,versioning_enabled)"
location: EUROPE-WEST1 name: PROJECT_ID-tfstate public_access_prevention: enforced uniform_bucket_level_access: true versioning_enabled: true
Common errors. If a field is missing in your SDK version, run the command without --format and read the full output. The field names in the output follow the gcloud storage resource format, which can differ slightly between releases.
gcloud storage buckets add-iam-policy-binding (write)
Purpose. Lets a pipeline service account read and write state objects. IAM changes are free.
gcloud storage buckets add-iam-policy-binding gs://PROJECT_ID-tfstate \ --member="serviceAccount:sa-bootstrap@PROJECT_ID.iam.gserviceaccount.com" \ --role="roles/storage.objectUser"
Flags. --member is the principal, --role the role; add --condition to limit the grant to an object-name prefix. roles/storage.objectUser allows reading and writing objects; the older roles/storage.objectAdmin also manages object ACLs and is broader than needed. Production use. Grant bucket-level roles to groups, not to people, and never grant roles/storage.admin to a pipeline.
terraform init -migrate-state
Purpose. Initialises the new GCS backend and copies the existing state into it. It writes to the bucket, which costs almost nothing.
terraform {
backend "gcs" {
bucket = "PROJECT_ID-tfstate"
prefix = "terraform/bootstrap"
# Optional: run as a service account instead of your own user.
# impersonate_service_account = "sa-bootstrap@PROJECT_ID.iam.gserviceaccount.com"
}
}
terraform init -migrate-state
Initializing the backend... Do you want to copy existing state to the new backend? Pre-existing state was found while migrating the previous "local" backend to the newly configured "gcs" backend. No existing state was found in the newly configured "gcs" backend. Do you want to copy this state to the new "gcs" backend? Enter "yes" to copy and "no" to start with an empty state. Enter a value: yes Successfully configured the backend "gcs"! Terraform will automatically use this backend unless the backend configuration changes.
Flags. -migrate-state copies state when the backend changes; -reconfigure ignores the old configuration and does not copy anything (use it only if you intend to start with the state that is already in the new backend); -force-copy answers yes automatically (use it in automation only). Common errors. Error 403: ... does not have storage.objects.list access means the identity lacks object roles on the bucket. bucket doesn't exist means a typo or the wrong project.
gcloud storage ls and terraform state list
Purpose. Confirm that the state object is in the bucket and that Terraform still sees all resources. Both are read-only and free.
gcloud storage ls --all-versions gs://PROJECT_ID-tfstate/terraform/bootstrap/ terraform state list
gs://PROJECT_ID-tfstate/terraform/bootstrap/default.tfstate#1732550000000000 gs://PROJECT_ID-tfstate/terraform/bootstrap/default.tfstate#1732550200000000
lifecycle { prevent_destroy = true } block on the bucket resource, and set an alert on the audit log for storage.buckets.delete and storage.objects.delete on this bucket.Lab: create a state bucket and migrate local state into it (about 15 minutes, low cost)
Goal. Create a protected state bucket in a sandbox project, run a tiny configuration with local state, then migrate its state to the bucket and prove that Terraform still manages the same resource.
Prerequisites. A sandbox project (PROJECT_ID) with billing linked and a budget set; roles/storage.admin on the project for the first steps (the sandbox owner has it). Cloud Shell or a workstation with Terraform 1.x. IDs in the expected output are illustrative. If you have no organization, everything in this lab still works because it uses one project.
- Confirm the project and enable the Storage API.
gcloud config set project PROJECT_ID gcloud services enable storage.googleapis.com gcloud config get-value project
- Create the bucket and turn on versioning. Verify with
describe:versioning_enabled: trueanduniform_bucket_level_access: true.gcloud storage buckets create gs://PROJECT_ID-tfstate --location=REGION --uniform-bucket-level-access --public-access-prevention gcloud storage buckets update gs://PROJECT_ID-tfstate --versioning gcloud storage buckets describe gs://PROJECT_ID-tfstate --format="yaml(name,versioning_enabled,uniform_bucket_level_access,public_access_prevention)"
- Create a small configuration with local state. It creates one extra bucket with a label, so there is something to track.
mkdir -p ~/tf-bootstrap && cd ~/tf-bootstrap cat > main.tf <<'EOF' terraform { required_version = ">= 1.5" required_providers { google = { source = "hashicorp/google" version = "~> 6.0" } } } variable "project_id" { type = string } variable "region" { type = string } provider "google" { project = var.project_id region = var.region } resource "google_storage_bucket" "demo" { name = "${var.project_id}-demo" location = var.region uniform_bucket_level_access = true public_access_prevention = "enforced" force_destroy = true labels = { env = "lab" purpose = "tf-bootstrap" } } EOF terraform init terraform apply -var="project_id=PROJECT_ID" -var="region=REGION"Verify:terraform state listprintsgoogle_storage_bucket.demoand the fileterraform.tfstateexists in the folder. - Add the backend block in a new file
backend.tfand migrate.cat > backend.tf <<'EOF' terraform { backend "gcs" { bucket = "PROJECT_ID-tfstate" prefix = "terraform/lab" } } EOF terraform init -migrate-stateAnsweryeswhen asked to copy the state. Verify: the messageSuccessfully configured the backend "gcs"!. - Prove the state is remote and complete.
gcloud storage ls gs://PROJECT_ID-tfstate/terraform/lab/ terraform state list terraform plan -var="project_id=PROJECT_ID" -var="region=REGION"
gs://PROJECT_ID-tfstate/terraform/lab/default.tfstate google_storage_bucket.demo No changes. Your infrastructure matches the configuration.
Expected: the state object is listed, the resource is in the state and the plan is empty. - Remove the local copies:
rm -f terraform.tfstate terraform.tfstate.backup. Runterraform planagain. Expected: stillNo changes, because the state now comes from the bucket. - Observe a lock: in a second terminal, start
terraform applyand wait at the confirmation prompt; in the first terminal run a plan. Expected:Error: Error acquiring the state lockwith the lock ID. Answernoat the prompt of the first run; the lock is released. - Test recovery. Overwrite the state by applying a label change, then list versions and restore the older one.
gcloud storage ls --all-versions gs://PROJECT_ID-tfstate/terraform/lab/default.tfstate
Expected: at least two generations listed. Restoring means copying an older generation back to the live name withgcloud storage cp gs://PROJECT_ID-tfstate/terraform/lab/default.tfstate#GENERATION gs://PROJECT_ID-tfstate/terraform/lab/default.tfstate(use only in recovery, with the lock free).
Cost. Low (usually well under a few USD per day for this lab; in practice a few cents). Two empty buckets and one tiny state object. Budgets send alerts and do not cap spend, so keep your budget alert from Hour 1 in place.
Cleanup. Destroy the demo bucket first, then remove the state bucket with its versions.
terraform destroy -var="project_id=PROJECT_ID" -var="region=REGION" gcloud storage rm --recursive gs://PROJECT_ID-tfstate cd ~ && rm -rf ~/tf-bootstrap
Verify cleanup: gcloud storage buckets list --project=PROJECT_ID shows neither bucket.
Real cases
- State in a team project. A team created its state bucket in a project where every developer had Editor. A developer cleaned up "old buckets" and deleted it. Moving the bucket to the seed project, enabling versioning and removing broad roles stopped the exposure; a delete alert now pages the platform team.
- Secret in the state. A module generated a database password and stored it as a resource attribute. The state was readable by a large group, so the password was exposed. The fix was to read secrets from Secret Manager at run time instead of generating them in Terraform, to restrict the bucket, and to rotate the password.
- Lock left behind. A pipeline job was cancelled during apply and left a lock. Everyone was blocked for an hour until someone ran
terraform force-unlock LOCK_ID. The team now documents the safe procedure: confirm that no run is active, then unlock, then run a plan before anything else.
Practices
- Create the bucket in the seed project with Terraform (with
prevent_destroy), uniform access, public access prevention and versioning. - Use one prefix per layer; grant each layer's service account access to its own prefix, or use one bucket per layer for strict separation.
- Add a lifecycle rule for non-current versions, and keep the bucket in a location that satisfies your residency policy.
- Alert on bucket deletion, on IAM changes of the bucket and on object deletes by anyone other than a pipeline identity (Hour 6 covers log-based alerts).
- Use impersonation (
impersonate_service_account) so that no key file ever holds access to the state.
terraform state pull into a shared folder. Remember that roles/storage.objectViewer on the bucket is enough to read every secret that the state holds.Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
Error acquiring the state lock | Another run is active, or a killed run left a lock | Check running pipelines; then gcloud storage ls gs://BUCKET/PREFIX/ for .tflock; unlock only with the lock ID and approval |
Error: Failed to get existing workspaces: ... 403 | Identity lacks storage.objects.list or get on the bucket | gcloud storage buckets get-iam-policy gs://BUCKET |
bucket doesn't exist / 404 | Typo in bucket, or the bucket is in another project and not visible | gcloud storage ls gs://BUCKET |
Backend configuration changed | The backend block was edited after init | Run terraform init -migrate-state (to copy) or -reconfigure (to switch without copying) |
| Plan wants to create everything after migration | The state was not copied (answered no, or used -reconfigure) | terraform state list; compare with the old terraform.tfstate; migrate again |
Variables may not be used here in the backend block | Backend blocks cannot use variables | Use literals or terraform init -backend-config=backend.hcl |
409 ... bucket name not available | Bucket names are global and the name is taken | Add the project ID or a random suffix to the name |
Triage order
- Is it the backend or the provider? Backend errors mention
gcs,stateorlockand occur at init or before refresh. - Which identity reads the bucket?
gcloud auth listand theimpersonate_service_accountsetting. - Does the object exist?
gcloud storage ls --all-versions gs://BUCKET/PREFIX/. - Is another run active? Look at the pipeline before touching a lock.
- Only then consider
force-unlock, and always runterraform planafterwards to confirm the state is intact.
These are search pages and official documents, not pinned video links, because videos age quickly. Check the date against the current Terraform backend documentation.
- YouTube search: Terraform GCS backend and state bucket
- YouTube search: Terraform state locking explained
- YouTube search: Cloud Storage object versioning
Official reading: Terraform GCS backend · Store Terraform state in a Cloud Storage bucket · Object versioning.
Module 3 · Providers and modules
- Pin Terraform and the Google provider with
required_version,required_providersand the dependency lock file. - Run
terraform fmt,validateandplan -outas a repeatable quality gate, and apply a saved plan. - Choose a module source (local path, registry or Git tag) and call a module with typed inputs and outputs.
The short answer
A reproducible Terraform run needs three things pinned: the Terraform version, the provider versions and the module versions. It also needs a repeatable quality gate: terraform fmt for style, terraform validate for syntax and types, and terraform plan -out to freeze the proposed change. This module covers all four, plus how to read and call a module.
What: the building blocks
required_versionconstrains the Terraform CLI version. Use a range such as">= 1.5, < 2.0", and have the pipeline use one exact CLI version from a container image.required_providersnames each provider, itssource(for examplehashicorp/google) and aversionconstraint (for example"~> 6.0", which allows every 6.x release and blocks 7.0).- Provider block sets defaults (
project,region) and the identity (for exampleimpersonate_service_account).user_project_override = truewithbilling_projectmakes API calls that need a quota project (such as Billing Budgets) charge that project. .terraform.lock.hclis written byinit. It records the provider version and the checksums of the packages. Commit it.- Variables, locals and outputs are the inputs, the internal names and the results of a configuration or module. Give every variable a
typeand adescription; usevalidationblocks for rules such as a naming pattern. - Modules are directories of
.tffiles called with amoduleblock. A module hasvariables.tf,main.tf,outputs.tfand a short README.
Why: reproducible, reviewable runs
- A provider release may add a new default or change behaviour. If the version floats, a plan that was empty yesterday can show changes today with no code change.
- A module changed upstream between the review and the apply is a supply-chain risk for something that controls your whole estate.
- A formatted, validated and saved plan makes review fast: reviewers read changes, not style.
How it works internally
initreadsrequired_providers, queries the registry for versions that satisfy the constraint, picks the newest, downloads it and writes the choice to the lock file. Later inits reuse the locked version until you runinit -upgrade.fmtparses the files and rewrites them with canonical indentation and alignment.-checkdoes not rewrite; it only reports.validatechecks that the configuration is internally consistent: argument names, types and references. It does not call the cloud API and needs no credentials onceinithas run.plan -out=tfplanauthenticates, refreshes state, computes the diff, and writes a binary plan file that bundles the configuration, the state snapshot ID and the proposed actions.apply tfplanchecks that the state still matches the snapshot. If not, it fails with a stale-plan error; otherwise it executes the actions.
Choosing a module source
| Source | Example | Pin with | Use when |
|---|---|---|---|
| Local path | ./modules/project | The Git commit of the repository | Your own modules in the same repository; fastest to change and review together |
| Terraform Registry | terraform-google-modules/project-factory/google | version = "~> X.Y" (the version you tested) | Well-maintained community or Google modules |
| Git over HTTPS | git::https://github.com/ORG/REPO.git//modules/project?ref=v1.2.0 | ?ref=TAG or a full commit hash | Internal modules shared across repositories |
| Private registry or artifact repository | Your internal registry address | A version constraint | Regulated environments that mirror every dependency |
The double slash // in a Git source separates the repository from the subdirectory inside it. After you change a module source or version, run terraform init again so the new copy is downloaded.
Writing a good module
- One purpose: "project", "subnet", "log sink". Avoid a module that takes fifty inputs and does everything.
- Inputs are typed, described and have safe defaults (for example
auto_create_network = false). Required inputs have no default so that callers cannot forget them. - Outputs expose what callers need (
project_id,project_number,service_account_email) and nothing else. - Do not put provider blocks inside reusable modules. The caller configures providers and passes them in if needed.
- Document with a short README and an example directory; run
terraform validateon the example in CI.
Confusion table
| Term | What it is | Often confused with |
|---|---|---|
required_version | Terraform CLI constraint | Provider version constraint |
.terraform.lock.hcl | Provider version and checksum record | State lock (a runtime marker in the backend) |
terraform validate | Static check of configuration | terraform plan, which also contacts the API |
terraform fmt | Style normaliser | A linter such as tflint, which finds likely mistakes |
| Module | Reusable directory called by a module block | Workspace, which is a separate state of the same configuration |
validate passed, so the plan will work." No. Validate cannot know whether a name is already taken, whether an API is enabled or whether the identity has the role. Only plan and apply talk to the API.-target to apply only the part I care about." Targeting skips dependencies and leaves the rest of the configuration unapplied. Reserve it for recovery and follow it with a full plan.Figure 1. The quality gate. Look at the order: cheap local checks run first and fail fast; the expensive, credentialed plan runs last; apply uses the artifact that was reviewed.
Figure 2. A root configuration owns the providers, the backend and the pinned versions. The module owns the pattern. Inputs go in; outputs come back.
The animation shows what happens when you run init and plan with a pinned provider: the version is resolved, downloaded, recorded in the lock file, configured, used to refresh a real resource, and finally the plan is written to a file. Each log line is typical Terraform output.
These commands make a Terraform run reproducible. They are all free to run; only apply can create billed resources.
Pin versions with required_version and required_providers
Purpose. Fixes the Terraform CLI range and the provider range. Put it in versions.tf in every layer.
terraform {
required_version = ">= 1.5, < 2.0"
required_providers {
google = {
source = "hashicorp/google"
version = "~> 6.0" # pin the major version you have tested
}
google-beta = {
source = "hashicorp/google-beta"
version = "~> 6.0" # only if you use beta-only features
}
}
}
provider "google" {
project = var.project_id
region = var.region
# Run as a service account, not a key file.
impersonate_service_account = var.terraform_service_account
}
Flags and arguments. ~> 6.0 allows 6.x and blocks 7.0. impersonate_service_account makes the provider request tokens for that service account; the caller needs roles/iam.serviceAccountTokenCreator on it. Common errors. Unsupported Terraform Core version means the CLI is outside required_version. Production use. Renovate or Dependabot proposes version bumps as pull requests, so upgrades are reviewed with a plan.
terraform fmt
Purpose. Rewrites .tf files to the canonical style. Local only; free.
terraform fmt -recursive # fix files in place terraform fmt -check -recursive # pipeline form: non-zero exit if anything differs
modules/project/main.tf envs/prod/main.tf
Flags. -recursive descends into subdirectories; -check reports without changing; -diff shows what would change. Common errors. Exit code 3 from -check means unformatted files exist (output lists them).
terraform validate
Purpose. Checks syntax, types and references. It needs init first so that provider schemas are available, but it does not call the cloud. Free.
terraform init -backend=false terraform validate
Success! The configuration is valid.
Flags. -json prints machine-readable diagnostics for pipelines. init -backend=false lets a pull-request check validate without access to the state bucket. Common errors. Unsupported argument usually means a typo or a provider version that predates the argument.
terraform plan -out and terraform show
Purpose. Creates the reviewable plan and prints it in a readable or machine-readable form. Free (read-only API calls).
terraform plan -out=tfplan
terraform show tfplan
terraform show -json tfplan | jq '.resource_changes[] | {address, actions: .change.actions}'
{
"address": "google_project.app_a",
"actions": ["create"]
}
Flags. -var-file, -var, -refresh=false (skips the refresh; use only to debug) and -lock-timeout=60s (wait for a lock instead of failing at once). Common errors. No value for required variable means a variable without a default was not supplied. Production use. The JSON plan feeds policy checks (Module 6) and a comment on the pull request.
terraform apply tfplan (write)
Purpose. Applies the reviewed plan. Cost depends on the resources in the plan; the plan summary line tells you what will be added.
terraform apply tfplan
Common errors. Saved plan is stale: the state changed after the plan; run plan -out again. Error: ... has been deleted during apply means a resource changed outside Terraform between plan and apply.
Call a module and read its outputs
Purpose. Shows the call pattern for a local module, a registry module and a Git module. Use only one source per module block.
module "project_local" {
source = "./modules/project"
name = "prj-app-a"
folder_id = var.prod_folder_id
labels = { env = "prod", team = "payments" }
}
module "project_registry" {
source = "terraform-google-modules/project-factory/google"
version = "~> X.Y" # replace with the release you have reviewed and tested
# inputs: see the module documentation
}
module "project_git" {
source = "git::https://github.com/ORG/REPO.git//modules/project?ref=v1.2.0"
name = "prj-app-b"
}
output "app_a_project_id" {
value = module.project_local.project_id
}
terraform init -upgrade only in a branch dedicated to dependency updates, and review the lock-file diff and the plan before merging.terraform providers lock
Purpose. Adds checksums for several platforms to the lock file, so a pipeline on Linux accepts a lock file created on a Mac or Windows laptop. Free.
terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64
Common errors. the cached package ... does not match any of the checksums means the lock file lacks the checksum for the platform in use; run this command and commit the result.
Lab: pin, format, validate and plan a small module (about 15 minutes, free to low cost)
Goal. Build a root configuration that calls a local module, pin its versions, run the full quality gate, save a plan and apply it. The module creates one labelled Cloud Storage bucket, so no organization is needed.
Prerequisites. A sandbox project with a budget alert; state bucket from Module 2 (or local state for this lab); Terraform 1.x; roles/storage.admin in the project. IDs in the expected output are illustrative.
- Create the structure.
mkdir -p ~/tf-modules/modules/labelled_bucket && cd ~/tf-modules
- Write the module in
modules/labelled_bucket.cat > modules/labelled_bucket/variables.tf <<'EOF' variable "name" { type = string description = "Globally unique bucket name." validation { condition = can(regex("^[a-z0-9][a-z0-9_.-]{2,62}$", var.name)) error_message = "Use 3-63 characters: lowercase letters, digits, dash, underscore, dot." } } variable "location" { type = string description = "Bucket location, for example europe-west1." } variable "labels" { type = map(string) description = "Labels applied to the bucket." default = {} } EOF cat > modules/labelled_bucket/main.tf <<'EOF' resource "google_storage_bucket" "this" { name = var.name location = var.location uniform_bucket_level_access = true public_access_prevention = "enforced" force_destroy = true labels = var.labels } EOF cat > modules/labelled_bucket/outputs.tf <<'EOF' output "bucket_url" { value = google_storage_bucket.this.url } EOF - Write the root configuration with pinned versions.
cat > versions.tf <<'EOF' terraform { required_version = ">= 1.5, < 2.0" required_providers { google = { source = "hashicorp/google" version = "~> 6.0" } } } EOF cat > main.tf <<'EOF' variable "project_id" { type = string } variable "region" { type = string } provider "google" { project = var.project_id region = var.region } module "bucket" { source = "./modules/labelled_bucket" name = "${var.project_id}-modlab" location = var.region labels = { env = "lab", owner = "platform" } } output "bucket_url" { value = module.bucket.bucket_url } EOF - Run the gate. Verify:
fmt -checkexits with 0 (runterraform fmt -recursivefirst if it lists files), andvalidateprintsSuccess! The configuration is valid.terraform fmt -recursive terraform init terraform fmt -check -recursive && echo "fmt ok" terraform validate cat .terraform.lock.hcl | head -12
fmt ok Success! The configuration is valid. # This file is maintained automatically by "terraform init". provider "registry.terraform.io/hashicorp/google" { version = "6.x.y" constraints = "~> 6.0" - Test the validation rule: set
name = "BAD NAME"inmain.tf, runterraform validateand read the error, then restore the correct value. Expected: the message fromerror_message. (Validation of variable rules for a module call runs at plan time if the value comes from a variable; with a literal,validatecatches it.) - Save and inspect the plan, then apply it.
terraform plan -var="project_id=PROJECT_ID" -var="region=REGION" -out=tfplan terraform show -json tfplan | grep -c '"create"' terraform apply tfplan
Verify:Plan: 1 to add, 0 to change, 0 to destroy.and, after apply,gcloud storage buckets describe gs://PROJECT_ID-modlab --format="value(labels)"shows the labels. - Make the plan stale on purpose. Run
terraform plan -out=old, then change a label in code, runterraform apply -auto-approve, and finally runterraform apply old. Expected: an error that the saved plan is stale. This is the protection that the pipeline relies on.
Expected result. A pinned, formatted, validated module call applied from a saved plan, with a lock file committed to the folder and a clear understanding of how a stale plan is rejected.
Cost. Low (usually well under a few USD per day; one empty bucket costs almost nothing). Budgets send alerts and do not cap spend.
Cleanup.
terraform destroy -var="project_id=PROJECT_ID" -var="region=REGION" cd ~ && rm -rf ~/tf-modules
Verify cleanup: gcloud storage buckets list --project=PROJECT_ID no longer shows PROJECT_ID-modlab.
Real cases
- The silent provider upgrade. A team had
version = ">= 5.0"and no lock file in Git. A new major release changed a default and the nightly plan suddenly proposed to replace a set of firewall rules. Pinning to the tested major version and committing the lock file removed the surprise, and upgrades became a pull request with a plan attached. - Module from the main branch. A platform module was referenced as
?ref=main. A well-meant change to a default broke twelve downstream configurations at the same moment. Tagging releases (semantic versions), referencing the tags and publishing a changelog turned each upgrade into a choice. - Pipeline on a different platform. Developers used laptops with ARM processors, the pipeline ran on Linux AMD64, and
initin the pipeline failed on checksums. Runningterraform providers lockwith all platforms once and committing the result fixed it for everyone.
Practices
- Pin
required_version,required_providersand every module; commit.terraform.lock.hcl. - Run
fmt -check,validateand optionallytflinton every pull request; run the plan with a read-only identity where possible. - Mirror external modules into an internal repository and review them like code you wrote; run them from your own tags.
- Keep modules small and version them with tags; document breaking changes.
- Use an automated dependency update tool so that upgrades are small and frequent, not rare and large.
local-exec provisioners that download and run scripts from the internet.Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
Unsupported Terraform Core version | The CLI is outside required_version | terraform version; update the CLI or the constraint |
Inconsistent dependency lock file | A provider constraint changed but the lock file did not | Run terraform init -upgrade on a branch, then review and commit the lock file |
does not match any of the checksums recorded | Lock file lacks the checksum for this platform | terraform providers lock -platform=... |
Module not installed / Module source has changed | Module source or version changed after init | Run terraform init again |
Unsupported argument or Missing required argument | Typo, or the provider version is older than the argument | Read the provider documentation for the pinned version; run validate |
Saved plan is stale | State changed after the plan | Create a new plan; check whether another run applied in between |
Error: Invalid value for variable | Your own validation rule rejected the value | Read the error_message; adjust the input |
Triage order
- Read the first error line and the file and line it names.
- Run
terraform versionandterraform providersto see what is actually installed. - Delete the local
.terraform/directory and runterraform initagain if you suspect a stale module or provider cache; keep the lock file. - Run
terraform validate; thenterraform plan. - If a plan suddenly shows unexpected changes, compare the lock file and module versions with the previous run before you change code.
These are search pages and official documents, not pinned video links, because video content ages quickly. Check the date against the provider documentation for your pinned version.
- YouTube search: Terraform provider version constraints and lock file
- YouTube search: Terraform modules best practices on Google Cloud
- YouTube search: Terraform fmt, validate and plan in CI
Official reading: Provider requirements · Dependency lock file · Module sources · Terraform best practices on Google Cloud.
Module 4 · Project factory
- Describe a project factory as a module that creates a project and everything it must have on day one: parent, billing, labels, APIs, budget, network attachment and service account.
- Write a map-driven project factory in HCL, including
auto_create_network = falseanddeletion_policy = "PREVENT". - Review a project-factory plan and decide whether it is safe to apply.
The short answer
A project factory (项目工厂) is Terraform that creates projects. A request is a few lines of data (name, team, environment, APIs, budget). The factory turns it into a project with the parent folder, the billing account, labels, enabled APIs, budget, network attachment and a dedicated service account, all configured the way the landing zone requires. It is the layer that application teams interact with most, so its quality decides how fast teams can move and how safe they are.
What a factory creates on day one
| Item | Terraform resource | Why it matters |
|---|---|---|
| Project in the right folder | google_project with folder_id | The folder carries inherited IAM and Organization Policy (Hours 2 and 3) |
| Unique project ID | project_id = prefix + random suffix | IDs are global, 6 to 30 characters, and cannot be changed or reused |
| Billing link | billing_account argument | No billing means no paid APIs; wrong billing means a wrong invoice |
| No default network | auto_create_network = false | Avoids the permissive default VPC (Hour 4) |
| Labels | labels = { env, team, cost-center } | Cost allocation, search and reporting (Hours 1 and 6) |
| Enabled APIs | google_project_service per API | Only the services the project needs, enabled on purpose |
| Budget and alerts | google_billing_budget | Early warning; budgets alert and do not cap spend |
| Shared VPC attachment | google_compute_shared_vpc_service_project | The project uses the central network (Hour 4) |
| Workload service account | google_service_account | No use of default service accounts; least-privilege roles are granted per project |
| Deletion protection | deletion_policy = "PREVENT" | A destroy or a removed block cannot delete the project |
Why a factory and not hand-made projects
- Speed with control. Teams ask in a pull request and get a ready project in minutes, with every control in place.
- Consistency. Naming, labels, APIs and budgets are the same everywhere, so reports and alerts work.
- Audit. Git history answers "who asked for this project, who approved it, and what did it look like".
- Safe removal. A project that is no longer needed leaves through a reviewed change, with its resources checked first.
How it works internally
- A request is added to a data file (for example
projects.auto.tfvarsor a YAML file read withyamldecode) as one entry in a map. - The factory module uses
for_eachover the map. For each entry it creates the project, then enables APIs, creates the budget, attaches Shared VPC and creates the service account. Terraform orders these by their references. - The pipeline identity of the projects layer performs the calls. It needs:
roles/resourcemanager.projectCreatoron the parent folder,roles/billing.useron the billing account,roles/compute.xpnAdminon the organization or folder for Shared VPC attachment, and the permission to create budgets on the billing account (roles/billing.costsManageror the narrower budget roles; check the current role list). - Outputs return the project ID, number and service account email, which the application layer reads (for example through
terraform_remote_stateor a data source).
Design decisions
| Decision | Options | Recommendation |
|---|---|---|
| How are requests expressed? | HCL map, YAML file, custom module inputs | One data file per team or environment; keep it readable by non-Terraform people |
| Project ID | Fixed name, or prefix plus random suffix | Prefix plus a random suffix avoids global collisions and name squatting; the display name stays human-friendly |
| Billing account | One for all, or one per business unit | As decided in Hour 1; the factory takes it as an input per environment |
| Who may merge requests? | Anyone, or CODEOWNERS | Platform team approves; a team may propose, never self-merge |
| Deletion | Allow destroy, or protect | Protect production (PREVENT); allow deletion in sandbox folders |
| Provider choice | Your own module, or the registry project-factory module | Start with a small module you own; adopt the community module when you need its breadth, pinned to a reviewed version |
Reviewing a project-factory plan
The plan is the control. Read it in this order:
- The summary line:
Plan: N to add, N to change, N to destroy.A request for one project should add a predictable number of resources. - Destroy and replace actions (
-and-/+). Any project replacement or deletion needs an explicit sign-off. - Parent and billing lines (
folder_id,billing_account): are they the right ones for the requested environment? - IAM changes (
google_project_iam_*): no basic roles (owner,editor), no individual users, only groups and service accounts. - APIs: only those needed; flag anything unusual (for example
compute.googleapis.comfor a pure data project). - Network attachment: the host project and the subnets match the environment.
deletion_policy only protects against Terraform. A person with resourcemanager.projects.delete can still delete it in the console. Combine it with least-privilege IAM and an audit alert for DeleteProject.gcloud projects undelete; its project ID cannot be reused afterwards.Figure 1. One request, four Google Cloud services. Look at the bottom row: each box is a separate API call that must succeed for the project to be complete.
Figure 2. The review order. The most dangerous lines come first, so a tired reviewer still catches them.
The animation follows one apply of the project factory: project creation, API enablement, billing link, budget, Shared VPC attachment and deletion protection. Notice that the APIs and the billing link depend on the project, which is why Terraform orders them after the first step.
The factory is HCL; gcloud is how you verify what it did. Verification commands are read-only and free. Creating projects, enabling APIs and budgets is free; resources that run inside a project are billed.
A map-driven project factory module
Purpose. One module call creates every project in the map. Put it in the projects layer with its own state prefix.
variable "billing_account_id" { type = string }
variable "host_project_id" { type = string }
variable "projects" {
description = "Project requests keyed by short name."
type = map(object({
folder_id = string
environment = string
team = string
apis = list(string)
budget_units = number # whole currency units per month
protect = optional(bool, true)
}))
}
resource "random_id" "suffix" {
for_each = var.projects
byte_length = 2 # 4 hex characters
}
resource "google_project" "this" {
for_each = var.projects
name = "prj-${each.key}"
project_id = "prj-${each.key}-${random_id.suffix[each.key].hex}"
folder_id = each.value.folder_id
billing_account = var.billing_account_id
auto_create_network = false
deletion_policy = each.value.protect ? "PREVENT" : "DELETE"
labels = {
env = each.value.environment
team = each.value.team
managed-by = "terraform"
}
}
locals {
project_apis = merge([
for k, p in var.projects : {
for api in p.apis : "${k}/${api}" => { project = k, api = api }
}
]...)
}
resource "google_project_service" "this" {
for_each = local.project_apis
project = google_project.this[each.value.project].project_id
service = each.value.api
disable_on_destroy = false
disable_dependent_services = false
}
resource "google_compute_shared_vpc_service_project" "this" {
for_each = var.projects
host_project = var.host_project_id
service_project = google_project.this[each.key].project_id
depends_on = [google_project_service.this]
}
resource "google_service_account" "workload" {
for_each = var.projects
project = google_project.this[each.key].project_id
account_id = "sa-workload"
display_name = "Workload identity for ${each.key}"
}
resource "google_billing_budget" "this" {
for_each = var.projects
billing_account = var.billing_account_id
display_name = "budget-${each.key}"
budget_filter {
projects = ["projects/${google_project.this[each.key].number}"]
}
amount {
specified_amount {
currency_code = "USD"
units = each.value.budget_units
}
}
threshold_rules { threshold_percent = 0.5 }
threshold_rules { threshold_percent = 0.9 }
threshold_rules { threshold_percent = 1.0 }
}
Notes. The google_project argument deletion_policy is available in recent provider releases; check the provider documentation for your pinned version, and use lifecycle { prevent_destroy = true } as a second guard on production. The random provider (hashicorp/random) must be in required_providers. Budgets need the Cloud Billing Budget API enabled in the quota project and the provider setting user_project_override = true with a billing_project. currency_code must match the billing account currency. Check the provider documentation for the exact arguments in your version.
Data file with the requests
Purpose. Teams change only this file. Real folder IDs and the billing account ID come from the environment layer.
# projects.auto.tfvars
projects = {
"app-a" = {
folder_id = "folders/FOLDER_ID"
environment = "prod"
team = "payments"
apis = ["compute.googleapis.com", "logging.googleapis.com", "monitoring.googleapis.com"]
budget_units = 500
}
"sandbox-1" = {
folder_id = "folders/SANDBOX_FOLDER_ID"
environment = "sandbox"
team = "platform"
apis = ["compute.googleapis.com"]
budget_units = 20
protect = false
}
}
gcloud projects describe
Purpose. Verifies the parent, state and labels of a factory project. Read-only and free.
gcloud projects describe PROJECT_ID --format="yaml(projectId,parent,labels,lifecycleState)"
labels: env: prod managed-by: terraform team: payments lifecycleState: ACTIVE parent: id: '987654321098' type: folder projectId: prj-app-a-4f7c
Common errors. PERMISSION_DENIED or project not found means a wrong ID or a missing resourcemanager.projects.get.
gcloud billing projects describe and gcloud services list
Purpose. Confirms the billing link and the enabled APIs. Both are read-only and free.
gcloud billing projects describe PROJECT_ID gcloud services list --enabled --project=PROJECT_ID --format="value(config.name)"
billingAccountName: billingAccounts/0X0X0X-0X0X0X-0X0X0X billingEnabled: true name: projects/PROJECT_ID/billingInfo projectId: PROJECT_ID compute.googleapis.com logging.googleapis.com monitoring.googleapis.com
gcloud billing budgets list
Purpose. Lists the budgets of a billing account, to see that the factory created one for the project. Read-only and free.
gcloud billing budgets list --billing-account=BILLING_ACCOUNT_ID
Common errors. Cloud Billing Budget API has not been used means the billingbudgets.googleapis.com API is not enabled in the quota project. Check gcloud billing budgets list --help for the flags in your SDK version.
gcloud compute shared-vpc associated-projects list
Purpose. Confirms that the project is attached to the host project. Read-only and free.
gcloud compute shared-vpc associated-projects list HOST_PROJECT_ID
RESOURCE_ID RESOURCE_TYPE prj-app-a-4f7c PROJECT
gcloud projects undelete (recovery)
Purpose. Restores a project in pending deletion within its recovery window. Free.
gcloud projects undelete PROJECT_ID
Production use. The factory pipeline never has resourcemanager.projects.delete on production folders; deletion is a rare, approved action by a separate role.
Lab: a mini project factory in a sandbox (about 15 minutes, free to low cost)
Goal. Create one sandbox project with labels, one enabled API, a budget and deletion protection using a module-style configuration, verify it with gcloud, then remove it safely.
Prerequisites. Permission to create a project and link billing: either roles/resourcemanager.projectCreator on a sandbox folder or, with no organization, the ability to create projects without a parent. roles/billing.user on BILLING_ACCOUNT_ID. Terraform 1.x. An existing project (QUOTA_PROJECT_ID) with billingbudgets.googleapis.com enabled if you want to try the budget. IDs in the expected output are illustrative.
- Prepare the folder and enable the budget API in the quota project (optional step).
mkdir -p ~/tf-factory && cd ~/tf-factory gcloud services enable billingbudgets.googleapis.com --project=QUOTA_PROJECT_ID
- Write the configuration. Without an organization, set
folder_idtonull(the project then has no parent).cat > main.tf <<'EOF' terraform { required_version = ">= 1.5, < 2.0" required_providers { google = { source = "hashicorp/google", version = "~> 6.0" } random = { source = "hashicorp/random", version = "~> 3.0" } } } variable "billing_account_id" { type = string } variable "quota_project_id" { type = string } variable "folder_id" { type = string default = null } provider "google" { user_project_override = true billing_project = var.quota_project_id } resource "random_id" "suffix" { byte_length = 2 } resource "google_project" "lab" { name = "factory-lab" project_id = "factory-lab-${random_id.suffix.hex}" folder_id = var.folder_id billing_account = var.billing_account_id auto_create_network = false deletion_policy = "PREVENT" labels = { env = "lab" team = "platform" managed-by = "terraform" } } resource "google_project_service" "logging" { project = google_project.lab.project_id service = "logging.googleapis.com" disable_on_destroy = false } resource "google_billing_budget" "lab" { billing_account = var.billing_account_id display_name = "budget-factory-lab" budget_filter { projects = ["projects/${google_project.lab.number}"] } amount { specified_amount { currency_code = "USD" units = "10" } } threshold_rules { threshold_percent = 0.5 } threshold_rules { threshold_percent = 1.0 } } output "project_id" { value = google_project.lab.project_id } EOF terraform init - Plan and review in the right order. Verify: the summary says
Plan: 4 to add(random id, project, service, budget), no destroy lines,auto_create_network = falseanddeletion_policy = "PREVENT"are visible.terraform plan -out=tfplan \ -var="billing_account_id=BILLING_ACCOUNT_ID" \ -var="quota_project_id=QUOTA_PROJECT_ID" \ -var="folder_id=FOLDER_ID" # omit this line when you have no organization
- Apply and verify with gcloud.
terraform apply tfplan gcloud projects describe $(terraform output -raw project_id) --format="yaml(projectId,parent,labels,lifecycleState)" gcloud billing projects describe $(terraform output -raw project_id) --format="value(billingEnabled)" gcloud services list --enabled --project=$(terraform output -raw project_id) --format="value(config.name)" | grep logging
lifecycleState: ACTIVE True logging.googleapis.com
- Test deletion protection. Run
terraform destroywith the same variables and read the error. Expected: an error saying that the project hasdeletion_policyset toPREVENTand cannot be destroyed until the policy is changed. - Remove the protection through a reviewed change: set
deletion_policy = "DELETE", runterraform plan -out=tfplan(Expected:1 to change), apply it, and then destroy.
Expected result. A project in the expected folder (or with no parent), with labels, billing, one API and a budget; a destroy attempt that is refused; and a clean removal after the protection is lifted by an explicit change.
Cost. Free for the project, the API and the budget. If you stop within the same day, the lab incurs no usage charges. Budgets send alerts and do not cap spend.
Cleanup.
terraform apply -var="billing_account_id=BILLING_ACCOUNT_ID" -var="quota_project_id=QUOTA_PROJECT_ID" -var="folder_id=FOLDER_ID" # after setting deletion_policy = "DELETE" terraform destroy -var="billing_account_id=BILLING_ACCOUNT_ID" -var="quota_project_id=QUOTA_PROJECT_ID" -var="folder_id=FOLDER_ID" cd ~ && rm -rf ~/tf-factory
Verify cleanup: gcloud projects list --filter="labels.team=platform AND labels.env=lab" shows no active factory-lab-* project (it may appear as DELETE_REQUESTED during the recovery window).
Real cases
- Projects by ticket. Platform engineers created every project by hand from tickets, which took days and left half of them without labels or budgets. A factory with a YAML request file cut the lead time to one review, and a scheduled report on missing labels dropped to zero.
- The accidental destroy. An engineer removed a block from a configuration to tidy it, and the plan quietly included the deletion of a production project. The reviewer missed it because the summary read "1 to destroy" among 40 lines. After the incident the team set
deletion_policy = "PREVENT"on production, added a CI rule that fails on any destroy ofgoogle_project, and required a second approver. - The project that could not be created. A request failed with a quota error on the billing account: the number of projects linked to one billing account was at its limit. The platform team requested a quota increase and, going forward, tracked projects per billing account as a metric.
Practices
- Keep the factory in its own layer with its own service account, state prefix and approval rules.
- Give the factory only what it needs:
projectCreatoron specific folders,billing.useron specific accounts, and no organization administrator. - Default every project to no default network, labels, a budget and a protected state; make exceptions visible in the data file.
- Add policy checks to the plan: fail on missing labels, on projects without a folder and on any basic-role grant (Module 6).
- Define a decommissioning process: remove workloads, remove the Shared VPC attachment, lift protection through a pull request, delete, and wait out the recovery window.
CreateProject and DeleteProject events from any other principal.Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
Error 403: The caller does not have permission on project create | Missing resourcemanager.projects.create on the parent | gcloud resource-manager folders get-iam-policy FOLDER_ID |
Error 409: Requested entity already exists | The project ID is taken or in the 30-day deletion window | Use a new random suffix; gcloud projects list --filter="projectId:prj-app-a*" |
Error setting billing account ... 403 | The identity lacks billing.resourceAssociations.create on the billing account | gcloud billing accounts get-iam-policy BILLING_ACCOUNT_ID |
Billing quota exceeded / link failed | Too many projects linked to one billing account | Check the quota in the console; request an increase or use another account |
Error 403: Cloud Billing Budget API has not been used | The budget API is not enabled in the quota project | gcloud services enable billingbudgets.googleapis.com --project=QUOTA_PROJECT_ID; set user_project_override |
| Shared VPC attachment fails | Missing roles/compute.xpnAdmin, or the host project is not enabled | gcloud compute shared-vpc get-host-project PROJECT_ID and the role on the org or folder |
| Default network appears anyway | auto_create_network was not set, or the project existed before | gcloud compute networks list --project=PROJECT_ID |
Cannot destroy ... deletion_policy | Protection works as designed | Change the policy through a reviewed change, then destroy |
Triage order
- Is it a permission issue? Identify the exact permission in the error and the scope where it is needed (folder, billing account, organization).
- Is an API disabled in the quota project or in the target project?
gcloud services list --enabled --project=.... - Is it a quota or a name collision? Read the error code (409 or a quota message).
- Re-run
terraform planafter a partial failure. Terraform records what succeeded; do not delete half-created projects by hand without checking the state. - Check the audit log for the denied call (Hour 6) to see which principal and permission were involved.
These are search pages and official documents, not pinned video links, because videos age quickly. Check the date against the provider and module documentation you use.
- YouTube search: Google Cloud project factory with Terraform
- YouTube search: Google Cloud budgets and alerts with Terraform
- YouTube search: Shared VPC service project attachment
Official reading: Project factory module on the Terraform Registry · google_project resource · Create and manage budgets · Creating and managing projects.
Module 5 · CI/CD for infrastructure
- Explain the plan-on-pull-request and apply-after-approval workflow and why the plan file is the artifact that is reviewed and applied.
- Configure a GitHub Actions or Cloud Build pipeline that authenticates to Google Cloud without a key file, using Workload Identity Federation and service account impersonation.
- Design one service account per Terraform layer, with the smallest roles that layer needs, and protect the apply step with an approval gate.
The short answer
A CI/CD pipeline for infrastructure (基础设施持续集成与交付) is the only supported path by which Terraform changes reach the landing zone. Engineers open a pull request, the pipeline runs terraform plan and posts the result, a reviewer approves, the code merges, and the pipeline runs terraform apply for the reviewed plan. Nobody runs apply from a laptop except in an emergency that is itself recorded.
What: the moving parts
- Source control: the repository is the single record of intent. The main branch is protected, so changes arrive only through reviewed pull requests.
- Pipeline runner: GitHub Actions, Cloud Build, GitLab CI or another system that runs Terraform in a clean, ephemeral environment.
- Identity: the runner obtains Google Cloud credentials through Workload Identity Federation (工作负载身份联合) and impersonates a service account (服务账号) that is specific to one Terraform layer.
- State backend: the Cloud Storage bucket from Module 2, with locking, so two runs cannot change the same state at once.
- Approval gate: a required human approval between plan and apply for sensitive layers.
Why: three problems it solves
- Review. A plan comment on a pull request turns "trust me" into evidence. A reviewer sees that a change will destroy a subnet before it happens.
- Consistency. The pipeline uses one Terraform version, one provider lock file and one identity, so "it worked on my machine" stops being an explanation.
- Least privilege. Humans do not need write access to production. The pipeline identity has the write roles, and its use is restricted by repository, branch and approval.
How it works internally: the two workflows
| Workflow | Trigger | Steps | Writes to Google Cloud? |
|---|---|---|---|
| Plan | Pull request that touches a layer folder | fmt -check, init, validate, plan -out=tfplan, post the plan summary, optional policy checks | No (read roles only, state lock only) |
| Apply | Push to main (after merge), usually with an approval gate | init, plan -out=tfplan again or load the reviewed plan, apply tfplan | Yes (write roles for that layer) |
Two designs are common. In the first, the apply workflow re-plans on the merged commit and applies that new plan after approval; the approver compares it with the pull request plan. In the second, the plan file from the pull request is stored as a build artifact and the apply job applies exactly that file. The second is stricter but must handle plans that go stale when another pull request merges first.
One service account per layer
The enterprise foundations blueprint splits Terraform into layers, each with its own state and its own pipeline identity. This is how the roles typically differ.
| Layer | What it manages | Service account scope | Typical roles (illustrative) |
|---|---|---|---|
| Bootstrap | State bucket, pipeline projects, the service accounts themselves | Organization and seed project; used rarely, by a small group | Folder Admin, Project Creator, Service Account Admin, Storage Admin on the seed project |
| Organization | Folders, Organization Policy, org log sinks | Organization | Organization Policy Administrator, Logging Admin, Folder Admin |
| Networks | Shared VPC host projects, subnets, firewall policies, NAT, DNS | Network folder | Compute Network Admin, Compute Shared VPC Admin, DNS Administrator |
| Projects | Project factory outputs | Environment folders | Project Creator, Billing User on the billing account, Project IAM Admin |
roles/owner "to make it work" turns a pull request into a path to full control. Start with no roles, run the plan, read the 403 errors, and add only the permissions that each error names.When to use which runner
| Runner | Choose it when | Authentication |
|---|---|---|
| GitHub Actions | Code lives in GitHub and you want pull-request comments, environments and required reviewers | Workload Identity Federation with google-github-actions/auth |
| Cloud Build | You want the pipeline inside Google Cloud, with private pools and no external identity provider | The build's service account, with a user-specified account per trigger |
| GitLab CI or another system | Your organization already standardises on it | Workload Identity Federation with that system's OIDC token |
Common misunderstandings
- "The plan on the pull request is what will happen." Only if the state does not change before apply. Other merges, console edits and API changes can make the real result differ, which is why the apply step plans again or uses a saved plan that fails when stale.
- "Workload Identity Federation means no secrets at all." The runner still needs permission to read modules and providers. It does remove the long-lived Google Cloud key, which was the largest secret.
- "CI makes review optional." CI makes review cheaper. Branch protection with a required reviewer is what makes it mandatory.
Figure 1. The two workflows share the same code path but not the same permissions. The plan job needs read roles; the apply job runs only after merge and approval.
Figure 2. Each pipeline impersonates only its own service account. The right-hand column is the scope where that account holds roles. A networks change can never touch organization policy.
Look at the arrows in Figure 2: no pipeline crosses to another layer's account. In Figure 1, find the two places where a human is involved (review and approval). Everything else is automated, and the identity path in the lower box shows that no step stores a key.
The animation follows a pull request from opening to the plan comment. Each step is a real call: the OIDC token exchange at Security Token Service, the impersonation call to IAM Credentials, and the lock on the state object in Cloud Storage. Notice that no step uses a key file.
Pipelines are configuration files, so most of this tab is workflow code. Commands that create identities are run once by the platform team, from the bootstrap layer, and they are free (IAM metadata only).
gcloud iam workload-identity-pools create (write, free)
Purpose. Creates the pool that trusts external identities. One pool per environment or per CI system is a common layout.
gcloud iam workload-identity-pools create github \ --project=PROJECT_ID \ --location=global \ --display-name="GitHub Actions"
Created workload identity pool [github].
Flags. --location=global is the only location for pools. --display-name is a label for people. The pool ID (github) is part of every principal name, so choose it deliberately. Check gcloud iam workload-identity-pools create --help for the flags in your SDK version.
Common errors. ALREADY_EXISTS for a pool that was deleted in the last 30 days (soft delete); undelete it or use a new ID. PERMISSION_DENIED needs roles/iam.workloadIdentityPoolAdmin.
gcloud iam workload-identity-pools providers create-oidc (write, free)
Purpose. Adds GitHub as an OIDC provider and maps token claims to attributes, with a condition that limits it to your repository.
gcloud iam workload-identity-pools providers create-oidc github-actions \ --project=PROJECT_ID \ --location=global \ --workload-identity-pool=github \ --issuer-uri="https://token.actions.githubusercontent.com" \ --attribute-mapping="google.subject=assertion.sub,attribute.repository=assertion.repository,attribute.ref=assertion.ref" \ --attribute-condition="assertion.repository == 'example-org/landing-zone'"
Created workload identity pool provider [github-actions].
Flags. --issuer-uri is the token issuer GitHub documents for Actions. --attribute-mapping copies claims from the token into attributes you can use in IAM. --attribute-condition is a CEL expression that must be true or the token is rejected. Without it, any GitHub repository can use the provider.
Production use. Add the branch or environment to the condition for production, for example assertion.repository == 'example-org/landing-zone' && assertion.ref == 'refs/heads/main', so a pull request from a feature branch cannot reach the apply identity.
gcloud iam service-accounts add-iam-policy-binding (write, free)
Purpose. Allows identities from the pool to impersonate one layer service account.
gcloud iam service-accounts add-iam-policy-binding \ sa-tf-networks@PROJECT_ID.iam.gserviceaccount.com \ --project=PROJECT_ID \ --role="roles/iam.workloadIdentityUser" \ --member="principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/github/attribute.repository/example-org/landing-zone"
Updated IAM policy for serviceAccount [sa-tf-networks@PROJECT_ID.iam.gserviceaccount.com]. bindings: - members: - principalSet://iam.googleapis.com/projects/123456789012/locations/global/workloadIdentityPools/github/attribute.repository/example-org/landing-zone role: roles/iam.workloadIdentityUser etag: BwYabc123= version: 1
Flags. --member uses principalSet with an attribute, so every job from that repository matches. PROJECT_NUMBER is the numeric project number, not the project ID. For one identity only, use principal://…/subject/SUBJECT.
Common errors. The binding is accepted even when the member string is wrong, and the failure shows up later as unable to impersonate. Copy the string from gcloud iam workload-identity-pools describe output and verify with a real run.
GitHub Actions: plan on pull request
Purpose. Runs format, validate and plan on every pull request that changes the networks layer, using Workload Identity Federation. Running the workflow costs nothing in Google Cloud; GitHub runner minutes follow your GitHub plan.
name: terraform-plan-networks
on:
pull_request:
paths: ["envs/networks/**"]
permissions:
contents: read
id-token: write # lets the job request a GitHub OIDC token
pull-requests: write # lets the job comment on the pull request
jobs:
plan:
runs-on: ubuntu-latest
defaults:
run:
working-directory: envs/networks
steps:
- uses: actions/checkout@v4
- id: auth
uses: google-github-actions/auth@v2
with:
workload_identity_provider: projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/github/providers/github-actions
service_account: sa-tf-networks@PROJECT_ID.iam.gserviceaccount.com
- uses: hashicorp/setup-terraform@v3
with:
terraform_version: 1.x
- run: terraform fmt -check -recursive
- run: terraform init -input=false
- run: terraform validate
- run: terraform plan -input=false -lock-timeout=60s -out=tfplan
- run: terraform show -no-color tfplan > plan.txt
- uses: actions/upload-artifact@v4
with:
name: tfplan-networks
path: envs/networks/plan.txt
Flags. id-token: write is required for the OIDC token and nothing more. -input=false stops Terraform from waiting for a prompt that nobody can answer. -lock-timeout=60s waits for another run to release the state lock instead of failing at once. -out=tfplan saves the plan.
Common errors. Unable to acquire OIDC token means id-token: write is missing from permissions. Permission 'iam.serviceAccounts.getAccessToken' denied means the principalSet binding does not match the token's repository. Pin actions to a major version (or a commit SHA for high-risk repositories) and check the current versions in each action's repository.
GitHub Actions: apply after approval
Purpose. Applies on merge to main. The environment key links the job to a GitHub environment that has required reviewers, so the job pauses until someone approves. This writes to Google Cloud; cost depends on the resources in the layer.
name: terraform-apply-networks
on:
push:
branches: [main]
paths: ["envs/networks/**"]
concurrency:
group: terraform-networks # never two applies for one layer
cancel-in-progress: false
permissions:
contents: read
id-token: write
jobs:
apply:
runs-on: ubuntu-latest
environment: production-networks # required reviewers set in repository settings
defaults:
run:
working-directory: envs/networks
steps:
- uses: actions/checkout@v4
- uses: google-github-actions/auth@v2
with:
workload_identity_provider: projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/github/providers/github-actions
service_account: sa-tf-networks-apply@PROJECT_ID.iam.gserviceaccount.com
- uses: hashicorp/setup-terraform@v3
with:
terraform_version: 1.x
- run: terraform init -input=false
- run: terraform plan -input=false -lock-timeout=60s -out=tfplan
- run: terraform apply -input=false -lock-timeout=60s tfplan
Design note. Splitting plan and apply into separate service accounts (sa-tf-networks with read roles, sa-tf-networks-apply with write roles) means a pull request from a branch can plan but never change anything. The concurrency group is a second safety on top of the state lock.
Cloud Build: plan step with a user-specified service account
Purpose. The same plan inside Google Cloud. The build runs as a dedicated service account and uses the Terraform image of your choice. Cloud Build minutes are metered after the free tier, so cost is low for short plans.
steps:
- id: init
name: hashicorp/terraform:TERRAFORM_VERSION
dir: envs/networks
args: ["init", "-input=false"]
- id: plan
name: hashicorp/terraform:TERRAFORM_VERSION
dir: envs/networks
args: ["plan", "-input=false", "-lock-timeout=60s", "-out=tfplan"]
serviceAccount: projects/PROJECT_ID/serviceAccounts/sa-tf-networks@PROJECT_ID.iam.gserviceaccount.com
options:
logging: CLOUD_LOGGING_ONLY
Flags. serviceAccount selects the identity for the whole build, so the default Cloud Build account is not used. CLOUD_LOGGING_ONLY is required when you set a user-specified service account without a logs bucket. Check the Cloud Build documentation for the current options fields.
Production use. Use a Cloud Build private pool when the pipeline must reach private endpoints, and put an approval on the apply trigger (--require-approval on the trigger) so a human decides before the build starts. Check gcloud builds triggers create --help for the flags in your SDK version.
gcloud iam service-accounts get-iam-policy (read, free)
Purpose. Audits who can impersonate a layer service account. Run it in a review, and after any change to the pool.
gcloud iam service-accounts get-iam-policy \ sa-tf-networks@PROJECT_ID.iam.gserviceaccount.com \ --project=PROJECT_ID
bindings: - members: - principalSet://iam.googleapis.com/projects/123456789012/locations/global/workloadIdentityPools/github/attribute.repository/example-org/landing-zone role: roles/iam.workloadIdentityUser etag: BwYabc123= version: 1
Common errors. An empty policy means nobody can impersonate the account, and the pipeline fails with a 403 at the auth step. A member such as allUsers or a whole domain is a finding: stop and fix it.
terraform plan -detailed-exitcode (read, free)
Purpose. Returns exit code 0 for no changes, 1 for an error and 2 for changes. A pipeline can use it to decide whether to post a comment or to open an approval request.
terraform plan -input=false -detailed-exitcode -out=tfplan; echo "exit=$?"
Plan: 2 to add, 1 to change, 0 to destroy. Saved the plan to: tfplan exit=2
Common errors. Some CI systems treat any non-zero exit as failure, so exit code 2 must be handled in the script, not left to the runner. Module 6 uses this flag for drift detection.
.github/workflows/ with CODEOWNERS and require a platform-team review, because whoever can change the workflow can change what the apply job does.Lab 5: a keyless plan pipeline on a sandbox project (about 20 minutes, low cost)
Goal. Create a Workload Identity pool and provider for a sandbox GitHub repository, create a read-only service account, and run a pull-request plan that authenticates without a key file.
Prerequisites.
- A sandbox Google Cloud project with a budget alert set first (Hour 1, Module 3). Budgets send alerts and do not cap spend.
- A private sandbox GitHub repository that you own, with a small Terraform folder
envs/sandbox(the lab in Module 7 provides one). No real secrets in the repository. - Roles on the sandbox project:
roles/iam.workloadIdentityPoolAdminandroles/iam.serviceAccountAdmin. - The
iam.googleapis.com,iamcredentials.googleapis.comandsts.googleapis.comAPIs enabled.
IDs in the expected output are illustrative.
- Set variables and enable the APIs. Verification: the list shows the three APIs.
export PROJECT_ID=PROJECT_ID export PROJECT_NUMBER=$(gcloud projects describe "$PROJECT_ID" --format="value(projectNumber)") gcloud services enable iam.googleapis.com iamcredentials.googleapis.com sts.googleapis.com --project="$PROJECT_ID" gcloud services list --enabled --project="$PROJECT_ID" --filter="name:(iam OR iamcredentials OR sts)" --format="value(config.name)"
iam.googleapis.com iamcredentials.googleapis.com sts.googleapis.com
- Create the pool and the provider (commands from the previous tab, with your repository in the condition). Verification:
gcloud iam workload-identity-pools providers describe github-actions \ --project="$PROJECT_ID" --location=global --workload-identity-pool=github \ --format="value(state,attributeCondition)"
ACTIVE assertion.repository == 'YOUR_ORG/YOUR_REPO'
- Create the plan service account and give it read access to the project. Verification: the policy shows the viewer role.
gcloud iam service-accounts create sa-tf-sandbox-plan --project="$PROJECT_ID" --display-name="Terraform sandbox plan" gcloud projects add-iam-policy-binding "$PROJECT_ID" \ --member="serviceAccount:sa-tf-sandbox-plan@$PROJECT_ID.iam.gserviceaccount.com" \ --role="roles/viewer"
- Allow the repository to impersonate it, then verify with
get-iam-policy.gcloud iam service-accounts add-iam-policy-binding \ "sa-tf-sandbox-plan@$PROJECT_ID.iam.gserviceaccount.com" \ --project="$PROJECT_ID" \ --role="roles/iam.workloadIdentityUser" \ --member="principalSet://iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/github/attribute.repository/YOUR_ORG/YOUR_REPO"
- Commit the plan workflow from the previous tab (adjust paths and names), push a branch, and open a pull request. Verification: in the GitHub Actions run, the step
Authenticate to Google Cloudsucceeds andterraform planprints a plan. - Negative test. Change the provider condition to a repository name that does not exist and re-run the job. Verification: the auth step fails with a message that the credential was rejected. Restore the condition and confirm the job passes again. This proves the condition is doing its job.
- Check the audit trail. Verification:
gcloud logging read 'protoPayload.serviceName="iamcredentials.googleapis.com" AND protoPayload.methodName="GenerateAccessToken"' \ --project="$PROJECT_ID" --limit=3 --freshness=1h \ --format="table(timestamp,protoPayload.authenticationInfo.principalSubject)"
Data Access audit logs for IAM Credentials may need to be enabled to see these entries; if the list is empty, check the audit log configuration in IAM and Admin.
Expected result. A pull request whose check passes, a plan comment or artifact, and a negative test that fails closed. No key file exists anywhere: gcloud iam service-accounts keys list --iam-account=sa-tf-sandbox-plan@PROJECT_ID.iam.gserviceaccount.com shows only the SYSTEM_MANAGED key.
Cost. Low (usually well under a few USD per day for this lab; the IAM objects are free, and runner minutes follow your GitHub plan).
Cleanup.
gcloud iam service-accounts delete "sa-tf-sandbox-plan@$PROJECT_ID.iam.gserviceaccount.com" --project="$PROJECT_ID" gcloud iam workload-identity-pools providers delete github-actions --project="$PROJECT_ID" --location=global --workload-identity-pool=github gcloud iam workload-identity-pools delete github --project="$PROJECT_ID" --location=global
Pool and provider deletion is a soft delete for 30 days, so the same ID cannot be reused until you undelete or choose a new ID. Delete the sandbox repository workflow files if you no longer need them.
Lab 5b (optional): add an approval gate
Create a GitHub environment named sandbox-apply with yourself as the required reviewer, point the apply workflow at it, push a change and watch the job wait for approval. Reject it once and confirm that no resource changed.
Real cases
- The key that lived in a repository secret. A team stored a service account key as a CI secret. When an engineer left, nobody knew whether the key had been copied, and rotation required a freeze across all pipelines. Moving to Workload Identity Federation removed the key, and an audit of
keys listbecame a single check that must return nothing user-managed. - One identity for every layer. A single pipeline account had Organization Administrator "because networks needed it once". A routine pull request changed an organization policy by accident. After the split into per-layer accounts, the networks pipeline could not edit policy, and the same mistake produced a clear
403in the plan instead of an incident. - Apply on an unreviewed branch. The apply workflow triggered on every branch push. Someone tested on a feature branch and changed production. Restricting the apply trigger to
main, adding an environment with required reviewers and addingrefto the provider condition made it impossible to apply from anywhere else.
Practices
- Protect
main: require pull requests, at least one reviewer who is not the author, and passing plan checks. Include administrators in the rule. - Use separate plan and apply identities where you can: plan with read roles, apply with write roles and an approval.
- Use a
concurrencygroup or equivalent so only one run per layer applies at a time, in addition to the state lock. - Pin Terraform, providers and third-party actions. Update them through pull requests that show the plan.
- Post the plan as a comment or artifact, and keep it for audit. Mask or exclude sensitive values; marking variables
sensitive = truehides them from plan output but not from state. - Protect the state bucket as strongly as the infrastructure: only layer identities and a small break-glass group may read or write it, and object versioning is on.
pull_request_target to run a plan on code from a fork with credentials. Never print tokens or the contents of GOOGLE_APPLICATION_CREDENTIALS in logs. Review who can edit workflow files and environment settings; that is equivalent to who can change production. Plans can contain secrets if the code reads them from data sources, so treat plan output as sensitive.Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
Unable to acquire OIDC token in the auth step | Workflow lacks permissions: id-token: write, or the job runs from a fork | Workflow permissions block; whether the event is pull_request from a fork |
The given credential is rejected by the attribute condition | Repository, ref or environment does not match the provider condition | gcloud iam workload-identity-pools providers describe … --format="value(attributeCondition)" |
Permission 'iam.serviceAccounts.getAccessToken' denied | Missing roles/iam.workloadIdentityUser binding or wrong principalSet string (project number versus ID) | gcloud iam service-accounts get-iam-policy SA_EMAIL |
403 on a Google API during plan | Layer service account lacks a read role, or the API is not enabled | Read the permission in the error; check gcloud services list --enabled |
Error acquiring the state lock | Another run is active, or a cancelled run left a lock | Check running workflows; see Module 8 for force-unlock |
| Apply says the plan is stale | State changed after the plan was saved | Re-run plan; check for another merge or a console change |
| Cloud Build fails with a logging error | User-specified service account with no logging option | Set options.logging to CLOUD_LOGGING_ONLY or provide a logs bucket |
Triage order
- Did the auth step succeed? If not, work the identity path in order: token permission, provider condition, impersonation binding.
- Did
initsucceed? If not, check backend bucket access and the module or provider download. - Did
planfail with a403? Add exactly the named permission to the layer account, through code in the bootstrap layer. - Did
applyfail while plan passed? Compare the read role of the plan account with the write role of the apply account. - Check Cloud Audit Logs for the denied call (
protoPayload.status.code=7) to see the exact principal and permission.
Video content changes often, so the links below are search pages rather than pinned videos. Check dates against the documentation you use.
- YouTube search: Terraform, GitHub Actions and Workload Identity Federation
- YouTube search: Terraform with Cloud Build
- YouTube search: plan on pull request workflow
Official reading: Workload Identity Federation · google-github-actions/auth · Store Terraform state in Cloud Storage.
Module 6 · Drift, policy checks and reviews
- Detect drift with a scheduled
terraform plan -detailed-exitcodeand decide whether to revert it in the cloud or accept it in code. - Bring an existing resource under Terraform control with an
importblock orterraform import, and confirm that the next plan is clean. - Describe how policy checks (plan validation, Policy Controller, Organization Policy) and a written review checklist stop unsafe changes at different stages.
The short answer
Drift (漂移) is the gap between the infrastructure that code and state describe and the infrastructure that actually exists. A landing zone has three ways to deal with it: detect it on a schedule, resolve it by either reverting the cloud or accepting the change into code, and prevent it with policy checks and reviews so there is less of it. This module covers all three.
What: where drift comes from
- Console or gcloud changes: an engineer opens a firewall during an incident and never closes it.
- Other automation: an autoscaler, a different Terraform workspace or a script changes labels or settings that your code also manages.
- Platform changes: Google Cloud adds a default value or a new attribute, and the provider reads it back as a difference after an upgrade.
- Resources that never entered code: projects and buckets created before the landing zone, which exist but have no state.
Why: drift is a process signal
If drift is not tracked, the repository stops describing reality, and the next apply may silently remove an emergency fix or, worse, reopen something that someone closed by hand. The goal is not zero drift but visible drift with an owner.
How it works internally
| Mechanism | What it does | Command or feature |
|---|---|---|
| Refresh | Reads every managed resource and updates the in-memory view of state | Part of plan; alone: terraform plan -refresh-only |
| Diff | Compares configuration with refreshed state and proposes changes | terraform plan |
| Signal | Turns the diff into an exit code for a job | -detailed-exitcode (0, 1 or 2) |
| Accept real values | Writes the refreshed values into state without changing infrastructure | terraform apply -refresh-only (use with care) |
| Adopt | Attaches an existing resource to a resource block | import block, terraform import |
| Rename without recreating | Tells Terraform that an address changed | moved block |
Deciding what to do with drift
| Situation | Decision | Action |
|---|---|---|
| Emergency change that should stay | Accept into code | Open a pull request that updates the code to match; the plan then shows no change |
| Unauthorised or mistaken change | Revert the cloud | Apply the code; record the incident and find out how the identity had write access |
| Attribute another system owns (for example autoscaling counts) | Stop managing it | Use lifecycle { ignore_changes = [...] } for that attribute, with a comment saying why |
| Resource that has no code | Import it or delete it | Write the block and an import block, then plan until clean |
terraform apply -refresh-only does not fix drift. It only updates state to match reality. The code still disagrees with reality, so the next normal plan will propose to change it back.Policy checks: three moments
| Moment | Type | Examples | What it can stop |
|---|---|---|---|
| Before merge (pull request) | Plan validation, linting, static analysis | terraform validate, a linter such as TFLint, policy checks against the plan JSON with Open Policy Agent (for example with Conftest), Terraform Validator through gcloud beta terraform vet, scanners such as Checkov | Unsafe code before anything exists |
| At request time (platform) | Preventive guardrails | Organization Policy constraints, IAM deny policies, VPC Service Controls, Policy Controller in GKE | Any create or update from any tool |
| After the fact | Detective controls | Security Command Center, Cloud Asset Inventory, scheduled drift plans, audit log alerts | Nothing is stopped, but violations are found quickly |
Use all three. Pull-request checks give fast feedback. Organization Policy makes the rule true for everyone. Detective controls catch what both missed.
The review: what a human adds
Automation checks rules you wrote. Reviewers check intent. A good review of a Terraform pull request asks: does the plan match the description, are there any destroys or replacements (-/+), which blast radius does this change have, does it touch IAM, networks or organization policy, and is there a rollback? The checklist in the production tab turns this into a repeatable routine.
Confused with
| Term | What it is | Not to be confused with |
|---|---|---|
| Terraform drift detection | Compares IaC state with real resources | Cloud Asset Inventory history, which records every change but knows nothing about your code |
| Policy Controller | Admission-time rules for Kubernetes (and Config Connector) resources | Organization Policy, which governs Google Cloud resources and API calls |
terraform import | Adopts a resource into state | Terraform creating or copying the resource |
Common misunderstandings
- "Drift detection needs a paid product." A nightly scheduled
planwith the detailed exit code is enough to start. - "Import writes the code for me." A plain import only updates state. You write the resource block, or you ask Terraform to draft one with
-generate-config-outand then review and clean it. - "Passing policy checks means safe." Rules cover what you thought of. Keep Organization Policy and reviews as separate layers.
Figure 1. A scheduled plan compares three things: the code, the state and the real resources. The exit code tells the job what to do next.
Figure 2. Preventive, pre-merge and detective controls cover different paths. Remove one and a class of change goes unchecked.
In Figure 1, follow the two arrows into terraform plan: it needs the state and the real resources at the same time. In Figure 2, notice that only the middle box sees changes made outside the pipeline before they happen.
The animation shows one nightly drift job. A firewall rule was widened by hand during the day. The job refreshes state, sees the real value, computes a plan with exit code 2 and alerts. No resource is changed by the job itself.
All commands in this tab that only plan, show or list are read-only and free. Commands that import or apply say so.
terraform plan -refresh-only (read, free)
Purpose. Shows what changed in the real world compared with state, without proposing to change infrastructure.
terraform plan -refresh-only -input=false
Note: Objects have changed outside of Terraform
Terraform detected the following changes made outside of Terraform since the
last "terraform apply" which may have affected this plan:
# google_compute_firewall.allow_ssh has changed
~ resource "google_compute_firewall" "allow_ssh" {
~ source_ranges = [
- "10.0.0.0/8",
+ "0.0.0.0/0",
]
# (10 unchanged attributes hidden)
}
Flags. -refresh-only compares state with reality only. -input=false is for CI. Common errors. Error: Failed to read … 403 means the plan identity lacks a read permission on that resource type.
terraform plan -detailed-exitcode (read, free)
Purpose. The scheduled drift check. Exit code 0 means clean, 2 means pending changes, 1 means error.
terraform plan -input=false -lock-timeout=60s -detailed-exitcode -out=drift.tfplan echo "exit=$?"
# google_compute_firewall.allow_ssh will be updated in-place
~ resource "google_compute_firewall" "allow_ssh" {
~ source_ranges = [
- "0.0.0.0/0",
+ "10.0.0.0/8",
]
}
Plan: 0 to add, 1 to change, 0 to destroy.
exit=2
Common errors. A runner that stops on any non-zero code never reaches your alert step. Capture the code in a variable instead. Production use. Run it per layer, at night, with a read-only identity, and send the summary line only (not the full plan) to the alert channel.
A scheduled drift workflow (GitHub Actions, read-only)
Purpose. Runs the drift check nightly and opens an alert when the exit code is 2. The plan identity has read roles only, so the job cannot change anything. Cost: runner minutes only.
name: terraform-drift-networks
on:
schedule:
- cron: "0 2 * * *" # 02:00 UTC every day
workflow_dispatch: {}
permissions:
contents: read
id-token: write
issues: write
jobs:
drift:
runs-on: ubuntu-latest
defaults:
run:
working-directory: envs/networks
steps:
- uses: actions/checkout@v4
- uses: google-github-actions/auth@v2
with:
workload_identity_provider: projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/github/providers/github-actions
service_account: sa-tf-networks-plan@PROJECT_ID.iam.gserviceaccount.com
- uses: hashicorp/setup-terraform@v3
with:
terraform_version: 1.x
terraform_wrapper: false
- run: terraform init -input=false
- id: plan
run: |
set +e
terraform plan -input=false -lock-timeout=60s -detailed-exitcode -no-color | tee plan.txt
echo "code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
- if: steps.plan.outputs.code == '2'
run: |
gh issue create --title "Drift detected: networks" \
--body "$(grep -E '^Plan:|will be' plan.txt | head -20)"
env:
GH_TOKEN: ${{ github.token }}
- if: steps.plan.outputs.code == '1'
run: exit 1
Flags. terraform_wrapper: false keeps the raw exit code. PIPESTATUS[0] reads the exit code of terraform even though its output goes through tee. Common errors. Scheduled workflows run only on the default branch and are paused after a long period without repository activity; check the Actions tab if the job stops appearing.
import block and terraform import (write to state, free)
Purpose. Adopts an existing bucket without recreating it. The import block form is reviewed in a pull request like any code, and Terraform 1.5 and later support it. Importing changes state only, not the bucket.
import {
to = google_storage_bucket.legacy
id = "PROJECT_ID/legacy-assets-bucket"
}
resource "google_storage_bucket" "legacy" {
name = "legacy-assets-bucket"
project = "PROJECT_ID"
location = "REGION"
uniform_bucket_level_access = true
labels = {
env = "prod"
owner = "platform"
}
}
terraform plan -input=false
google_storage_bucket.legacy: Preparing import... [id=PROJECT_ID/legacy-assets-bucket] google_storage_bucket.legacy: Refreshing state... [id=legacy-assets-bucket] Plan: 1 to import, 0 to add, 0 to change, 0 to destroy.
Flags. The id format differs per resource type; the provider documentation for each resource has an Import section that lists the accepted forms. The older CLI form is terraform import google_storage_bucket.legacy PROJECT_ID/legacy-assets-bucket. Common errors. Cannot import non-existent remote object means the ID is wrong. If the plan shows 1 to change after the import, the code does not match the real bucket: edit the code until the plan is clean, and do not apply a change you did not intend.
terraform plan -generate-config-out (draft code, free)
Purpose. Asks Terraform to draft resource blocks for import blocks that have no matching resource. Always review the output; it can include defaults and computed values that you should remove.
terraform plan -input=false -generate-config-out=generated.tf
Check terraform plan -help for the options in your Terraform 1.x version before relying on this.
terraform state list and terraform state show (read, free)
Purpose. Lists what state manages, and shows the stored attributes of one resource. Use them to confirm an import and to answer "is this resource under Terraform?".
terraform state list terraform state show google_storage_bucket.legacy
google_storage_bucket.legacy google_compute_firewall.allow_ssh
Common errors. State can contain secret values, so restrict who may run state show against production state.
gcloud beta terraform vet (read, free)
Purpose. Validates a Terraform plan against constraint templates (Terraform Validator). The command is in the beta group and its flags can change, so check gcloud beta terraform vet --help in your SDK version. A typical flow converts the plan to JSON and passes it with a policy library.
terraform show -json tfplan > tfplan.json gcloud beta terraform vet tfplan.json --policy-library=policy-library --format=json
Common errors. If the component is missing, install it with the gcloud component manager as the help text describes. Production use. Run it in the plan workflow and fail the check when violations exist.
moved block (code, free)
Purpose. Renames a resource address (for example when you refactor into a module) without destroying and recreating it.
moved {
from = google_compute_network.hub
to = module.network.google_compute_network.hub
}
Lab 6: detect, import and block (about 20 minutes, low cost)
Goal. Use the sandbox configuration from Module 7 (or any tiny configuration with one labelled bucket), create drift by hand, detect it with the exit code, import a bucket that was created outside Terraform, and write one policy check against the plan.
Prerequisites. A sandbox project with a budget alert set first, a state bucket and a working Terraform configuration with one google_storage_bucket that has labels (Module 7 builds it step by step, so do Module 7 first if you have no configuration yet). Roles: roles/storage.admin on the sandbox project. No real secrets. IDs in the expected output are illustrative.
- Confirm a clean baseline. Verification:
terraform plan -detailed-exitcodeprintsNo changes.andecho $?prints0. - Create drift by hand: change a label with gcloud.
gcloud storage buckets update gs://BUCKET_NAME --update-labels=env=hacked --project=PROJECT_ID
Verification:gcloud storage buckets describe gs://BUCKET_NAME --format="value(labels)"showsenv=hacked. - Detect it. Verification:
terraform plan -input=false -detailed-exitcode; echo "exit=$?"
~ labels = { ~ "env" = "hacked" -> "sandbox" } Plan: 0 to add, 1 to change, 0 to destroy. exit=2 - Resolve it by reverting:
terraform apply, then repeat the plan. Verification: exit code 0 and the label is back tosandbox. - Create an unmanaged bucket and import it. Bucket names are global, so add a suffix you own.
gcloud storage buckets create gs://BUCKET_NAME-legacy --project=PROJECT_ID --location=REGION --uniform-bucket-level-access
Add theimportblock and the matching resource from the commands tab (change names to yours). Verification: the plan shows1 to import, 0 to add, 0 to change. Apply, then runterraform state listand confirm the new address appears. - Write a simple policy check on the plan JSON. Create
policy/deny_public.rego(open source Open Policy Agent syntax) and run it with Conftest if you have it, or read it as an exercise if you do not.package main deny[msg] { rc := input.resource_changes[_] rc.type == "google_storage_bucket" rc.change.after.uniform_bucket_level_access != true msg := sprintf("bucket %s must enable uniform bucket-level access", [rc.address]) }terraform plan -input=false -out=tfplan terraform show -json tfplan > tfplan.json conftest test tfplan.json --policy policy
1 test, 1 passed, 0 warnings, 0 failures, 0 exceptions
Now setuniform_bucket_level_access = falsein code, repeat, and confirm the check fails with your message. Revert the change.
Expected result. You have seen exit code 0, 2 and an import plan with 1 to import, and a policy that fails a bad plan before apply.
Cost. Low (usually well under a few USD per day for this lab: two empty buckets).
Cleanup. Remove the import block, run terraform destroy for the sandbox configuration (this deletes the labelled and the imported bucket; they must be empty), and verify with gcloud storage buckets list --project=PROJECT_ID. Delete the policy folder if you do not need it.
Real cases
- The firewall rule that stayed open. During an outage an engineer opened SSH to the internet by hand. Three weeks later the nightly drift job flagged it, the incident record explained why it was opened, and the team reverted it through the pipeline. Without the job the rule would have remained until an audit found it.
- Hundreds of unmanaged projects. A company adopted Terraform after years of console use. Rather than import everything at once, it imported by risk: shared networks and IAM first, then projects in production folders, with a weekly report from Cloud Asset Inventory listing resources that had no label saying
managed_by=terraform. Coverage rose steadily and nobody had to freeze work. - The policy that blocked a good change. A plan check required a label on every project, and a legitimate pull request failed because the check read a variable incorrectly. The team added a documented exception process (a reviewed allow-list in the policy repository) rather than disabling the check, and fixed the rule.
Practices
- Run drift detection per layer, nightly for production and weekly for sandboxes. Send alerts to a channel that someone owns.
- Give every drift alert an owner and a due date. Track "accepted into code" versus "reverted" so you can see why drift happens.
- Use
ignore_changesonly for attributes that another system owns, and always add a comment. - Use
prevent_destroyand deletion protection on state buckets, log buckets and production projects. - Keep policy rules in their own repository with tests (known good and known bad plans) and review rule changes like production code.
- Use a review checklist (below) and put it in the pull request template.
Review checklist for infrastructure pull requests
- Does the plan match the description? Read every line, not only the summary.
- Any
destroyor-/+(replace)? Is data affected? Is there a backup? - Does it change IAM, organization policy, firewall or routes? Who else must approve?
- Which layers and environments are touched? Is the blast radius what the author says?
- Are new resources labelled for cost and owner, and in the right folder and region?
- Are provider and module versions pinned, and is the lock file updated deliberately?
- Is there a rollback plan, and has the change been tried in a lower environment first?
terraform state rm without a second reviewer; that makes Terraform forget protections such as deletion protection and can lead to duplicate resources.Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
| Plan shows changes you did not make, on every resource | Provider upgrade changed defaults or attribute handling | Compare .terraform.lock.hcl in Git history; read the provider changelog |
Cannot import non-existent remote object | Wrong import ID format or wrong project | The Import section of the resource documentation; gcloud … describe of the object |
After import the plan wants to replace the resource (-/+) | A force-new attribute (for example name or location) differs from the real one | Read the # forces replacement line; correct the code, do not apply |
| Drift job exits 1 instead of 2 | Provider or backend error, or a missing read permission | Read the first error in the log; check the plan identity roles |
| Same drift reappears every night | Another system keeps changing the attribute | Find the writer in audit logs; use ignore_changes if it is legitimate |
| Policy check passes locally but fails in CI | Different policy versions or plan JSON built with different variables | Compare the policy commit and the -var-file used in both places |
Error acquiring the state lock during a drift run | An apply is running or a previous job was cancelled | Check active workflows; wait; see Module 8 |
Triage order
- Is it a real difference or a provider or version change? Look at the lock file and provider version first.
- Who made the change? Query the audit log for the resource:
gcloud logging read 'protoPayload.resourceName:"firewalls/allow-ssh"' --limit=5 --freshness=7d. - Decide: revert, accept into code, or stop managing the attribute. Write the decision in the pull request.
- Re-run the plan until it exits 0. Never leave a layer with an unexplained pending plan.
Video content changes often, so the links below are search pages rather than pinned videos. Check dates against the documentation you use.
- YouTube search: Terraform drift detection and import
- YouTube search: policy as code for Terraform plans
- YouTube search: Policy Controller on Google Cloud
Official reading: Terraform import · Validate policies for Terraform on Google Cloud · Organization Policy overview.
Module 7 · Lab: Terraform in a sandbox
- Create a versioned state bucket and a remote backend, then initialise a small Terraform configuration against it.
- Run plan, apply and destroy, and prove each step with a gcloud command and with the state file stored in Cloud Storage.
- Clean up every resource in the right order, and verify that nothing billable remains.
The short answer
This module is a guided lab. You will use everything from Modules 1 to 3: a remote state bucket (远程状态存储桶), a pinned provider, fmt, validate and plan -out. You will also meet the lifecycle in the order a landing-zone pipeline uses it: bootstrap the state bucket once, init a layer against it, plan, apply, verify, destroy.
What you will build
| Item | Purpose | Created by | Removed by |
|---|---|---|---|
State bucket PROJECT_ID-tfstate-sandbox | Remote state with versioning and uniform bucket-level access | gcloud storage buckets create (bootstrap) | gcloud storage rm at the end |
Demo bucket PROJECT_ID-lz-demo | One small resource with labels, to prove the workflow | Terraform | terraform destroy |
Configuration folder tf-sandbox/ | The code: versions.tf, backend.tf, main.tf, variables.tf, outputs.tf | You | You (local files) |
Why this order
- The state bucket cannot be created by the configuration that stores its state in it. It is created first, by a command or by a bootstrap layer.
- Labels are the cheapest control to practise: they cost nothing, show in billing exports and are visible in every
describeoutput. - A bucket is a small, nearly free resource, so the lab teaches the full cycle without meaningful spend.
How the pieces connect
- The backend block says where state lives (bucket and prefix). Terraform reads it at
init. - The provider block says which project and region the Google provider uses, and how it authenticates (here: your own credentials from
gcloud auth application-default login, or impersonation of a service account). - The resource block describes the demo bucket. Terraform compares it with state and with reality, and proposes the difference.
- Apply sends the API call, then writes the new state object to Cloud Storage and removes the lock.
Mapping to the pipeline you built in Module 5
| In the lab | In the landing zone |
|---|---|
You run terraform plan by hand | The pull-request job runs it and posts the result |
| You approve by typing the plan file name | A reviewer approves the environment before the apply job runs |
| You use your own Application Default Credentials | The job impersonates a layer service account through Workload Identity Federation |
| You destroy at the end | Production layers use deletion protection and prevent_destroy |
terraform destroy is not "undo". It deletes real resources and, for data stores, their data. Run it only in the sandbox, read the plan, and never point it at a state that manages production.Safety rules for every lab
- Use a sandbox project that contains nothing you need, with a budget alert set first. Budgets send alerts; they do not cap spend.
- Use no real secrets. Nothing in this lab needs one.
- Print the project before you start:
gcloud config get-value project. Most accidents are the right command in the wrong project.
Figure 1. What the lab creates. The state bucket is created outside Terraform; the demo bucket is created and destroyed by Terraform.
Figure 2. The seven steps of the lab are the same steps a pipeline performs. Learn them once by hand.
In Figure 1, notice that the state bucket sits outside the configuration, on its own. That is why it is created with gcloud and removed last. In Figure 2, the verify step is a separate stage: a successful apply is not proof until a second plan reports no changes.
The animation shows one run of the lab from init to verification. Pay attention to the order: the lock is taken before the plan, the API call happens during apply, and the state is written before the lock is released. The gcloud check at the end is independent proof from outside Terraform.
These are the commands you will use in the lab. Variables used below: PROJECT_ID (sandbox project), REGION (for example a region close to you). Write commands say whether they cost money; in this lab the cost is low.
gcloud storage buckets create (write, low cost)
Purpose. Creates the state bucket with versioning-ready, uniform bucket-level access and public access prevention.
gcloud storage buckets create gs://PROJECT_ID-tfstate-sandbox \ --project=PROJECT_ID \ --location=REGION \ --uniform-bucket-level-access \ --public-access-prevention
Creating gs://PROJECT_ID-tfstate-sandbox/...
Flags. --uniform-bucket-level-access disables per-object ACLs, so IAM is the only access model. --public-access-prevention blocks public access. Bucket names are globally unique, so adding the project ID helps. Common errors. HTTPError 409: Your previous request to create the named bucket succeeded and you already own it means you are re-running the command; 409 … name is not available means another project owns the name.
gcloud storage buckets update --versioning (write, free)
Purpose. Turns on object versioning for the state bucket so a damaged state can be recovered.
gcloud storage buckets update gs://PROJECT_ID-tfstate-sandbox --versioning
Updating gs://PROJECT_ID-tfstate-sandbox/... Completed 1
Common errors. AccessDeniedException: 403 means you lack storage.buckets.update (included in roles/storage.admin).
terraform init (free)
Purpose. Downloads the provider, configures the gcs backend and writes the lock file.
terraform init -input=false
Initializing the backend... Successfully configured the backend "gcs"! Terraform will automatically use this backend unless the backend configuration changes. Initializing provider plugins... - Finding hashicorp/google versions matching "~> 6.0"... - Installing hashicorp/google v6.x.x... - Installed hashicorp/google v6.x.x (signed by HashiCorp) Terraform has been successfully initialized!
Flags. -input=false turns prompts into errors, which is what pipelines need. -migrate-state (Module 2) is used only when moving existing local state. Common errors. Error: Failed to get existing workspaces: storage: bucket doesn't exist means the bucket name in backend.tf is wrong or not yet created.
terraform fmt -check and terraform validate (free)
terraform fmt -check -recursive terraform validate
Success! The configuration is valid.
Common errors. fmt -check prints the names of files that need formatting and exits 3; run terraform fmt -recursive to fix them.
terraform plan -out (read, free)
Purpose. Creates the saved plan that you review and then apply.
terraform plan -input=false -out=tfplan
Terraform will perform the following actions:
# google_storage_bucket.demo will be created
+ resource "google_storage_bucket" "demo" {
+ force_destroy = true
+ labels = {
+ "env" = "sandbox"
+ "managed_by" = "terraform"
+ "owner" = "platform"
}
+ location = "REGION"
+ name = "PROJECT_ID-lz-demo"
+ uniform_bucket_level_access = true
...
}
Plan: 1 to add, 0 to change, 0 to destroy.
Saved the plan to: tfplan
terraform apply tfplan (write, low cost)
Purpose. Applies exactly the saved plan. No prompt is shown, because the plan was the review.
terraform apply -input=false tfplan
google_storage_bucket.demo: Creating... google_storage_bucket.demo: Creation complete after 2s [id=PROJECT_ID-lz-demo] Apply complete! Resources: 1 added, 0 changed, 0 destroyed. Outputs: bucket_url = "gs://PROJECT_ID-lz-demo"
Common errors. Error 403: … does not have storage.buckets.create access means your identity lacks the role. Error: Saved plan is stale means the state changed after the plan; re-plan.
gcloud storage buckets describe and gcloud storage ls (read, free)
Purpose. Independent verification that the bucket exists with the expected labels, and that state is in the state bucket.
gcloud storage buckets describe gs://PROJECT_ID-lz-demo --format="yaml(name,location,labels,uniform_bucket_level_access)" gcloud storage ls gs://PROJECT_ID-tfstate-sandbox/sandbox/
labels: env: sandbox managed_by: terraform owner: platform location: REGION name: PROJECT_ID-lz-demo uniform_bucket_level_access: true gs://PROJECT_ID-tfstate-sandbox/sandbox/default.tfstate
terraform destroy (write, removes resources)
Purpose. Deletes everything in state, in dependency order. In the lab this removes the demo bucket.
terraform destroy -input=false -auto-approve
google_storage_bucket.demo: Destroying... [id=PROJECT_ID-lz-demo] google_storage_bucket.demo: Destruction complete after 1s Destroy complete! Resources: 1 destroyed.
Flags. -auto-approve skips the prompt; use it only in a lab, never in a production pipeline. Common errors. Error: Error trying to delete bucket … containing objects without force_destroy set to true means the bucket has objects and force_destroy is false.
destroy against them.Lab 7: Terraform in a sandbox (about 25 minutes of work, low cost)
Goal. Take one small configuration through the full lifecycle against a remote state bucket, verify each step, and clean up completely.
Prerequisites.
- A sandbox project that you may delete from, with a budget alert set first (budgets alert, they do not cap spend).
- Cloud Shell (it has
gcloudand Terraform installed) or a local shell with both. Check withgcloud versionandterraform version; Terraform must be 1.x. roles/storage.adminandroles/serviceusage.serviceUsageAdminon the sandbox project.- No real secrets and no data of value in the project. IDs in the expected output are illustrative.
- Set the project and check it.
gcloud config set project PROJECT_ID gcloud config get-value project gcloud services enable storage.googleapis.com serviceusage.googleapis.com
Verification: the second command prints your sandbox project ID, andgcloud services list --enabled --filter="name:storage.googleapis.com"lists the API. - Authenticate Terraform. In Cloud Shell, Application Default Credentials already work. Elsewhere run
gcloud auth application-default login. Verification:gcloud auth application-default print-access-token | head -c 12prints the first characters of a token (do not share it). - Create and protect the state bucket (commands from the previous tab: create, then
--versioning). Verification:gcloud storage buckets describe gs://PROJECT_ID-tfstate-sandbox --format="yaml(versioning,uniform_bucket_level_access,public_access_prevention)"
public_access_prevention: enforced uniform_bucket_level_access: true versioning: enabled: true
- Write the configuration. Create a folder and the files below.
mkdir -p tf-sandbox && cd tf-sandbox
versions.tfterraform { required_version = ">= 1.5" required_providers { google = { source = "hashicorp/google" version = "~> 6.0" } } }backend.tf(a backend block cannot use variables, so write the bucket name literally)terraform { backend "gcs" { bucket = "PROJECT_ID-tfstate-sandbox" prefix = "sandbox" } }variables.tfvariable "project_id" { type = string description = "Sandbox project ID" } variable "region" { type = string description = "Region for the demo bucket" } variable "labels" { type = map(string) default = { env = "sandbox" owner = "platform" managed_by = "terraform" } }main.tfprovider "google" { project = var.project_id region = var.region } resource "google_storage_bucket" "demo" { name = "${var.project_id}-lz-demo" location = var.region uniform_bucket_level_access = true public_access_prevention = "enforced" force_destroy = true labels = var.labels }outputs.tfoutput "bucket_url" { value = "gs://${google_storage_bucket.demo.name}" }terraform.tfvars(values only, no secrets)project_id = "PROJECT_ID" region = "REGION"
Verification:terraform fmt -check -recursiveprints nothing andterraform init -input=falseends withTerraform has been successfully initialized!. Thenterraform validateprintsSuccess! The configuration is valid. - Plan and review. Run
terraform plan -input=false -out=tfplan. Verification: the summary isPlan: 1 to add, 0 to change, 0 to destroy.Read thelabelsblock: it must show the three labels. - Apply the saved plan. Run
terraform apply -input=false tfplan. Verification:Apply complete! Resources: 1 added, 0 changed, 0 destroyed.and the outputbucket_url. Then check with gcloud (buckets describein the previous tab) that the labels are present. - Check idempotency. Run
terraform plan -detailed-exitcode. Verification:No changes. Your infrastructure matches the configuration.and exit code 0. - Inspect state in Cloud Storage.
gcloud storage ls -l gs://PROJECT_ID-tfstate-sandbox/sandbox/ gcloud storage cat gs://PROJECT_ID-tfstate-sandbox/sandbox/default.tfstate | head -20
4021 2026-01-15T09:12:44Z gs://PROJECT_ID-tfstate-sandbox/sandbox/default.tfstate
Verification: the object exists and the first lines show"version": 4and"terraform_version". State is plain JSON; this is why access to the bucket must be restricted. Also rungcloud storage ls --all-versions gs://PROJECT_ID-tfstate-sandbox/sandbox/to see generations (versioning in action). - Change one label and see an in-place update. In
variables.tfchangeowner = "platform"toowner = "network-team", then runterraform plan -out=tfplanandterraform apply tfplan. Verification: the plan shows~ "owner" = "platform" -> "network-team"andPlan: 0 to add, 1 to change, 0 to destroy.; after apply, thedescribeoutput shows the new owner. Note that the state object has a new generation. - Destroy the demo bucket. Run
terraform destroy -input=false, read the plan (Plan: 0 to add, 0 to change, 1 to destroy.), typeyes. Verification:gcloud storage buckets list --project=PROJECT_ID --format="value(name)"no longer listsPROJECT_ID-lz-demo. - Remove the state bucket last. It has object versions, so remove it with
gcloud storage rm --recursive, which deletes the bucket and every object version. Only do this for the sandbox state bucket.gcloud storage rm --recursive gs://PROJECT_ID-tfstate-sandbox
Verification:gcloud storage buckets list --project=PROJECT_IDshows no buckets from this lab, andterraform state listnow fails to find the backend, which is expected.
Expected result. You have created, changed and destroyed a resource through Terraform, seen the state object appear, change and be versioned in Cloud Storage, and removed everything.
Cost. Low (usually well under a few USD per day for this lab; two nearly empty regional buckets, deleted within the hour). Confirm in Billing after a day that the sandbox project shows no residual spend.
Cleanup checklist.
- Demo bucket destroyed by Terraform (step 11).
- State bucket removed with
gcloud storage rm --recursive(step 12). - Local folder
tf-sandbox/deleted if you do not need it:cd .. && rm -rf tf-sandbox. - Optional: disable unused APIs, and delete the sandbox project if it was created only for the course.
Stretch goals (optional)
- Run steps 7 to 9 again with
-lock-timeout=60s, then try a second terminal at the same time to see the lock message. - Add a second bucket with
for_eachover a set of names and watch the plan show two creations. - Make a deliberate error (wrong region) and read the error before fixing it.
Real cases
- The lab that became production. A team built a working sandbox, kept the local state file on a laptop and later copied the code into a shared repository. The laptop state was lost and the resources had to be imported one by one. The remote backend from the first lab command would have avoided it.
- State bucket deleted by project cleanup. A cleanup script deleted all buckets named like "tmp" in a project. The state bucket had a similar name. Versioning let the team restore the last generation, and a retention policy plus a label such as
purpose=terraform-stateexcluded the bucket from future scripts. - A destroy that was meant for the sandbox. An engineer ran
terraform destroyin a shell whose backend pointed to the shared network state. The plan was long and was not read. After this, the team protected critical resources withprevent_destroy, required a typed project ID in the runbook, and removed destroy permissions from human accounts in non-sandbox projects.
Practices
- Create the state bucket in a dedicated seed or automation project, with versioning, uniform bucket-level access, public access prevention and a tight IAM policy.
- Keep one prefix per layer and environment (for example
networks/prod), and one service account per prefix. - Pin the provider and commit the lock file. Review lock file changes in pull requests.
- Use labels for owner, environment and cost centre on every resource, so billing exports can attribute spend.
- Keep human
destroyfor sandboxes only. In production, destroy goes through a pull request.
terraform.tfstate or tfplan to Git: add both to .gitignore. Do not create service account keys to "make Terraform work"; use Application Default Credentials, impersonation or Workload Identity Federation.Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
Failed to get existing workspaces: storage: bucket doesn't exist | Backend bucket name typo or bucket not created | gcloud storage ls gs://BUCKET |
Error 403: … storage.objects.get on init | Your identity cannot read the state bucket | gcloud storage buckets get-iam-policy gs://BUCKET |
Error: Backend configuration changed | You edited backend.tf after init | Run terraform init -reconfigure (or -migrate-state if moving state) |
Error 409: … name is not available creating the demo bucket | Bucket names are global; someone owns this name | Change the suffix in name |
Error 403: Cloud Storage API has not been used in project | API not enabled | gcloud services enable storage.googleapis.com |
| Plan shows the bucket will be created again after destroy and apply | Expected: destroy removed it | Compare with the state object generations |
Error acquiring the state lock | Another run, or an interrupted run | Wait; then terraform force-unlock LOCK_ID only if no run is active |
| The wrong project received the bucket | project_id variable or gcloud config project mismatch | gcloud config get-value project; read terraform.tfvars |
Triage order
- Read the first error line; Terraform prints the failing API call and HTTP code.
- Check the identity and the project:
gcloud auth list,gcloud config get-value project. - Check that the API is enabled and your role includes the permission named in the error.
- Check the state:
terraform state listand the object in the bucket. - Only then change code. Re-run
validateandplan.
Video content changes often, so the links below are search pages rather than pinned videos. Check dates against the documentation you use.
- YouTube search: Terraform with the Cloud Storage backend
- YouTube search: Terraform on Google Cloud in Cloud Shell
Official reading: Get started with Terraform on Google Cloud · Terraform gcs backend · Google provider documentation.
Module 8 · Troubleshooting IaC
- Read a Terraform error from the Google provider and place it in the right layer: state and backend, API enablement, identity and roles, provider and versions, or real-world drift.
- Release a stuck state lock safely, and enable a missing API through code instead of by hand.
- Apply a fixed triage order to an HTTP 403, a failed pipeline and an unexpected plan, and say what to check first.
The short answer
Almost every Terraform failure on Google Cloud belongs to one of five layers. If you decide which layer first, you check the right thing first. Reading the first error line, not the last, is half of the work, because later errors are often consequences.
What: the five layers
| Layer | Typical symptom | Typical cause | Where to look |
|---|---|---|---|
| 1. State and backend (状态) | Error acquiring the state lock, Failed to get existing workspaces, Backend configuration changed | Stale lock, wrong bucket or prefix, bucket permissions | The lock info in the error; gcloud storage ls on the bucket |
| 2. API enablement | Error 403: … API has not been used in project … or it is disabled | Service not enabled in the project that is billed; Service Usage API itself disabled | gcloud services list --enabled |
| 3. Identity and roles | 403 … permission … denied, unable to impersonate | Missing role on the layer service account, trust path broken, deny policy, Organization Policy | The permission in the error; get-iam-policy; audit log |
| 4. Provider and versions | Plan shows changes nobody made; Unsupported argument; Inconsistent dependency lock file | Provider or module upgrade, a different Terraform version, a lock file not committed | .terraform.lock.hcl, terraform version, changelog |
| 5. Real-world drift | Plan proposes to undo someone's change; apply fails with already exists | Console edits, another automation, resources created outside Terraform | plan -refresh-only, audit log, Cloud Asset Inventory |
Why a fixed order helps
Under pressure people change code first. Errors in layers 1 to 3 are not code errors: changing code does nothing. A fixed order stops this and makes handovers easy: everyone says "layer 3, missing compute.networks.create on the networks account".
How to read a Google provider error
Error: Error creating Network: googleapi: Error 403: Required 'compute.networks.create' permission for 'projects/PROJECT_ID/global/networks/hub', forbidden
with google_compute_network.hub,
on network.tf line 3, in resource "google_compute_network" "hub":
3: resource "google_compute_network" "hub" {
- HTTP code:
403forbidden (identity or API),404not found (wrong name, project or region),409already exists or conflict,400invalid argument,429quota or rate limit. - Permission or API name:
compute.networks.createis the exact permission to give (through a role). - Resource and file line:
with google_compute_network.hub, on network.tf line 3tells you which block failed.
The 403 decision tree
- Does the message say the API is disabled or
SERVICE_DISABLED? Enable the API in the project named in the message. - Does it name a permission? Find which principal made the call (the audit log shows
principalEmail), and check that principal's roles on the resource and its parents. - Is the principal the one you expect? In a pipeline, the Terraform identity might be the layer service account, a different one from the one you tested with.
- Could a deny policy, an IAM Condition (for example an expired time condition) or an Organization Policy be involved? Policy Troubleshooter and the Policy Denied audit log say so.
- Was the role granted recently? IAM changes can take a few minutes to take effect everywhere; retry after waiting.
Confused with
| Error | Often mistaken for | Difference |
|---|---|---|
403 SERVICE_DISABLED | A missing role | The caller may be fully allowed; the service is off in that project |
404 notFound on a resource you know exists | A deleted resource | Wrong project, region or ID, or the caller cannot see it (some APIs return 404 instead of 403) |
409 already exists | A Terraform bug | The resource was created outside Terraform; import it |
| State lock error | A state corruption | It is a lock record, not a damaged state |
Common misunderstandings
- "Run it again, it is probably transient." 403, 404 and 409 are almost never transient. Only
429and some5xxcodes are worth a retry. - "Grant Owner so it passes." That hides the real missing permission and removes least privilege. Add exactly the permission in the error.
- "Delete the state and re-import." That is the last resort and loses protections such as deletion flags. Fix the cause (lock, backend, identity) first.
Figure 1. Five layers, one triage. Identify the layer from the first error line before any change is made.
Figure 2. A pipeline 403 can come from five points along the identity path. Follow the path from left to right and stop at the first one that fails.
In Figure 1, the red box (identity) is the most common source of surprises in a landing zone, because several controls meet there. In Figure 2, the failure text under each box is what you will actually see in the log; match it to a box before changing anything.
The animation replays a stale lock followed by a missing API. It shows what the runner prints, how the lock holder is identified in the message, and how the denied call appears in Cloud Audit Logs with status code 7 (permission denied).
Diagnostic commands here are read-only and free unless marked. Lock release and API enablement are writes; both are free of charge themselves, but enabling an API makes the service available for billable use.
terraform force-unlock (write to the lock only, free)
Purpose. Removes a stale state lock after you have confirmed that no run is in progress.
terraform force-unlock 1736930000123456
Do you really want to force-unlock? Terraform will remove the lock on the remote state. This will allow local Terraform commands to modify this state, even though it may still be in use. Only 'yes' will be accepted to confirm. Enter a value: yes Terraform state has been successfully unlocked!
Flags. The argument is the lock ID printed in the error. -force skips the prompt; avoid it by hand. Common errors. Failed to unlock state: … lock ID does not match means the lock was replaced by another run; check again who is running. Production use. Require a note in the incident ticket with the lock ID and the person who confirmed that no run was active.
gcloud storage ls on the lock object (read, free)
Purpose. The gcs backend stores the lock as an object next to the state. Seeing it proves the lock exists and shows when it was created.
gcloud storage ls -l gs://PROJECT_ID-tfstate/networks/prod/
9812 2026-01-15T09:12:44Z gs://PROJECT_ID-tfstate/networks/prod/default.tfstate
189 2026-01-15T09:30:02Z gs://PROJECT_ID-tfstate/networks/prod/default.tflock
Common errors. AccessDeniedException: 403 means your identity cannot list the bucket; ask the platform team rather than widening access.
gcloud services list --enabled (read, free)
Purpose. Shows which APIs are enabled on the project named in the error.
gcloud services list --enabled --project=PROJECT_ID --filter="config.name:(compute OR serviceusage OR run)" --format="value(config.name)"
compute.googleapis.com serviceusage.googleapis.com
Common errors. If this command itself fails with a 403, the Service Usage API is disabled or you lack serviceusage.services.list. The project in the error message is the project billed for the call, which can be the quota project rather than the resource project.
gcloud services enable (write, free to enable)
Purpose. Enables an API once, to unblock a bootstrap. For the long term, enable APIs in code with google_project_service.
gcloud services enable run.googleapis.com --project=PROJECT_ID
Operation "operations/acf.p2-123456789012-abc" finished successfully.
resource "google_project_service" "run" {
project = var.project_id
service = "run.googleapis.com"
disable_on_destroy = false
}
Flags. disable_on_destroy = false keeps the API enabled when the resource is destroyed, which avoids breaking other resources that use it. Common errors. Enabling can fail with FAILED_PRECONDITION when billing is not linked or an Organization Policy restricts services; check the project billing link first.
gcloud logging read for denied calls (read, free)
Purpose. Finds the exact principal and permission of a denied API call, which is more reliable than guessing from the Terraform message.
gcloud logging read 'protoPayload.status.code=7 AND protoPayload.authenticationInfo.principalEmail:"sa-tf-"' \ --project=PROJECT_ID --freshness=1h --limit=5 \ --format="table(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.methodName,protoPayload.resourceName)"
TIMESTAMP PRINCIPAL_EMAIL METHOD_NAME RESOURCE_NAME 2026-01-15T09:14:02.100Z sa-tf-networks@PROJECT_ID.iam.gserviceaccount.com v1.compute.networks.insert projects/PROJECT_ID/global/networks/hub
Flags. Status code 7 is PERMISSION_DENIED. Common errors. Empty output may mean Data Access logs are not enabled for that service, or that the denial was a client-side error before the call. Policy Denied logs appear under cloudaudit.googleapis.com%2Fpolicy.
gcloud policy-troubleshoot iam (read, free)
Purpose. Explains whether a principal has a permission on a resource and which policies contribute. Check gcloud policy-troubleshoot iam --help for the flags in your SDK version.
gcloud policy-troubleshoot iam //cloudresourcemanager.googleapis.com/projects/PROJECT_ID \ --principal-email=sa-tf-networks@PROJECT_ID.iam.gserviceaccount.com \ --permission=compute.networks.create
access: NOT_GRANTED explainedPolicies: - access: NOT_GRANTED fullResourceName: //cloudresourcemanager.googleapis.com/projects/PROJECT_ID ...
terraform providers lock and terraform version (free)
Purpose. Check which Terraform and provider versions run, and write checksums for the platforms your team and runners use.
terraform version terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64
Terraform v1.x.x on linux_amd64 + provider registry.terraform.io/hashicorp/google v6.x.x
Common errors. Error: Failed to install provider … does not match any of the checksums recorded in the dependency lock file means the lock file lacks checksums for the runner platform; run providers lock for that platform and commit the result.
terraform plan -refresh-only and terraform state (free)
terraform plan -refresh-only -input=false terraform state list | head
Purpose. Separate "real world changed" (layer 5) from "code or provider changed" (layer 4). See Module 6.
Lab 8: break it and fix it (about 20 minutes, low cost)
Goal. Reproduce three common failures in the sandbox from Module 7 and fix each with the triage order: a disabled API, a stale lock and a missing role.
Prerequisites. The sandbox project and the tf-sandbox configuration from Module 7 (recreate the state bucket if you removed it). A second service account is needed for the role test. Budget alert set first (alerts do not cap spend). No real secrets. IDs in the expected output are illustrative.
- Break layer 2: disable an API that only the demo uses. Enable Secret Manager, add a
google_secret_manager_secretresource withsecret_id = "lz-demo-secret"andreplication { auto {} }tomain.tf, and apply it. Then disable Secret Manager and plan. Never disable Cloud Storage in this lab: the state bucket depends on it.gcloud services enable secretmanager.googleapis.com --project=PROJECT_ID gcloud services disable secretmanager.googleapis.com --project=PROJECT_ID terraform plan -input=false
Error: Error when reading or editing Secret Manager Secret "lz-demo-secret": googleapi: Error 403: Secret Manager API has not been used in project 123456789012 before or it is disabled.
Triage: the HTTP code is 403 and the text says the API is disabled, so this is layer 2. Fix:gcloud services enable secretmanager.googleapis.com --project=PROJECT_ID, wait a minute and plan again. Verification:terraform plansucceeds. Note that the state bucket uses Cloud Storage, so a disabled Cloud Storage API would block the whole lab; that is why this step uses Secret Manager. - Break layer 1: create a stale lock. Start an apply that waits for confirmation in terminal 1, then run a plan in terminal 2.
# terminal 1 (leave it at the prompt, do not type yes) terraform apply # terminal 2 terraform plan -lock-timeout=5s
Error: Error acquiring the state lock Error message: writing "gs://PROJECT_ID-tfstate-sandbox/sandbox/default.tflock" failed: googleapi: Error 412: At least one of the pre-conditions you specified did not hold., conditionNotMet Lock Info: ID: 1736930000123456 Path: gs://PROJECT_ID-tfstate-sandbox/sandbox/default.tflock Operation: OperationTypeApply Who: user@cloudshell
Triage: the lock holder is your own terminal 1, so a run is active; do not unlock. Answernoin terminal 1 to cancel the apply (the lock is released), and run the plan again. Verification: the second plan succeeds. To practise the force-unlock path, kill terminal 1 with Ctrl+C twice while the apply prompt is shown, confirm that no other run exists, then runterraform force-unlock LOCK_IDwith the ID printed. - Break layer 3: a missing role. Create a service account with no roles and run a plan as it, using impersonation.
gcloud iam service-accounts create sa-tf-norole --project=PROJECT_ID gcloud iam service-accounts add-iam-policy-binding sa-tf-norole@PROJECT_ID.iam.gserviceaccount.com \ --project=PROJECT_ID --member="user:YOUR_EMAIL" --role="roles/iam.serviceAccountTokenCreator" export GOOGLE_IMPERSONATE_SERVICE_ACCOUNT=sa-tf-norole@PROJECT_ID.iam.gserviceaccount.com terraform plan -input=false
Error: Failed to get existing workspaces: querying Cloud Storage failed: googleapi: Error 403: sa-tf-norole@PROJECT_ID.iam.gserviceaccount.com does not have storage.objects.list access to the Google Cloud Storage bucket. Permission 'storage.objects.list' denied on resource (or it may not exist).
Triage: layer 3, identity. The message names the principal, the permission and the bucket. Fix: grant the narrow role on the state bucket only, then plan again.gcloud storage buckets add-iam-policy-binding gs://PROJECT_ID-tfstate-sandbox \ --member="serviceAccount:sa-tf-norole@PROJECT_ID.iam.gserviceaccount.com" \ --role="roles/storage.objectAdmin"
Verification: the next plan reaches the Google provider and then fails with a different 403 (for example onstorage.buckets.getfor the demo bucket). Each new error is the next missing permission. Stop when you have seen the pattern, and note that a real layer account gets a planned set of roles in code, not trial and error in production. - Read the evidence in the audit log.
gcloud logging read 'protoPayload.status.code=7' --project=PROJECT_ID --freshness=30m --limit=3 \ --format="table(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.methodName)"
Verification: the denied calls showsa-tf-noroleas the principal. If the list is empty, Data Access logs for Cloud Storage may be off; the Admin Activity entries for IAM changes are always on.
Expected result. You reproduced layers 1, 2 and 3, named each from the error text, and fixed it at the right layer, without changing Terraform code.
Cost. Low (usually well under a few USD per day for this lab; one small bucket and some API calls).
Cleanup.
unset GOOGLE_IMPERSONATE_SERVICE_ACCOUNT terraform destroy -input=false gcloud iam service-accounts delete sa-tf-norole@PROJECT_ID.iam.gserviceaccount.com --project=PROJECT_ID gcloud storage rm --recursive gs://PROJECT_ID-tfstate-sandbox
Verify with gcloud storage buckets list --project=PROJECT_ID and gcloud iam service-accounts list --project=PROJECT_ID.
Real cases
- The lock left by a cancelled job. A CI run was cancelled while applying, and every later run failed on the lock. An engineer forced the unlock without checking that the cancelled job was truly gone; the runner was still finishing its apply, and the state was overwritten by a second run. After this, the runbook required checking running jobs and the lock's creation time, the apply workflow used a
concurrencygroup, and cancel-in-progress was disabled for apply. - The API that was disabled in a new project. The project factory created projects without the Service Usage API enabled, and the first pipeline run in each new project failed with a 403. The fix was in code: the factory enabled
serviceusage.googleapis.comand a baseline list of APIs throughgoogle_project_service, and the failure disappeared from onboarding. - A provider upgrade that changed a hundred projects. An unpinned provider moved to a new major version and the next nightly plan wanted to change many resources. Because the lock file was committed, the team could see the version change, roll it back in one pull request, and then upgrade deliberately with a plan review.
- The service account without a role. A new layer pipeline failed on
403in the first run. The team added roles through the bootstrap code, one permission at a time from the errors, and recorded the final role list in the layer's README so future reviewers knew the intent.
Practices
- Write the triage order and these commands as a runbook next to the code, and put the link in the pipeline failure message.
- Have the pipeline print the identity it uses (the service account email) at the start of every run. It removes a whole class of confusion.
- Prefer lock timeout (
-lock-timeout=60s) in CI, so short overlaps wait instead of failing. - Enable the baseline APIs in code in the project factory, and do not rely on people enabling them by hand.
- Alert on Policy Denied and permission-denied audit events for pipeline service accounts, so a missing role is seen before an engineer reports it.
roles/owner or roles/editor to fix a 403; add the narrow role named in the error. Do not disable Organization Policy to get a plan through. If you must force-unlock or edit state, record who did it and why, and get a second person to review it.Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
Error acquiring the state lock | Another run is active, or an earlier run was cancelled | Lock Info in the message; active workflows; gcloud storage ls -l on the prefix |
Error 403: … API has not been used in project … or it is disabled | Service not enabled in the billed project | gcloud services list --enabled --project=PROJECT_ID |
Error 403: … permission … denied | Layer service account lacks a role, or the call comes from the wrong principal | Audit log status.code=7; policy-troubleshoot iam |
Error 403: Request is prohibited by organization's policy | VPC Service Controls perimeter or an Organization Policy | Policy Denied log; VPC Service Controls violation details (unique ID in the message) |
Error 404: … not found for a resource that exists | Wrong project, region or ID; or API hides existence | gcloud … describe with the same ID and project |
Error 409: … already exists | Resource created outside Terraform | Import it (Module 6) or choose a new name |
Error 429 / quota exceeded | Rate limit or quota | Quota page for the API; add retry or reduce parallelism with -parallelism=N |
Inconsistent dependency lock file or Unsupported argument after a merge | Provider version differs between branches or machines | .terraform.lock.hcl diff; terraform init -upgrade only on purpose |
| Plan wants to revert a manual change | Console drift | terraform plan -refresh-only; audit log for who changed it |
| Apply says saved plan is stale | State changed after the plan | Another merge or a manual change; re-plan |
Triage order
- Read the first error line: HTTP code, permission or API, resource, file line.
- Name the layer (state, API, identity, versions, drift) before touching anything.
- Print the identity and the project in use:
gcloud auth list,gcloud config get-value project, or the service account in the pipeline log. - Collect evidence: audit log for status code 7,
services list, lock object, lock file diff. - Fix in the right layer, with the narrowest change. Put the fix in code where possible.
- Re-run plan until it is clean. Record the cause and the prevention in the incident note.
Video content changes often, so the links below are search pages rather than pinned videos. Check dates against the documentation you use.
- YouTube search: Terraform state lock and force-unlock
- YouTube search: Terraform Google provider 403 troubleshooting
- YouTube search: IAM Policy Troubleshooter
Official reading: Troubleshoot access in IAM · terraform force-unlock · Enable and disable services.
Command cheat sheet
Hour 7 command cheat sheet: infrastructure as code and automation
Use this page during the labs and in the pipeline runbook. Placeholders are in UPPERCASE: PROJECT_ID, PROJECT_NUMBER, REGION, BUCKET_NAME. Write commands change real resources; the cost column says whether they cost money. Check gcloud … --help and terraform … -help for the flags in your installed version.
Terraform: daily workflow
| Command | Purpose | Key flags | Gotcha |
|---|---|---|---|
terraform fmt -check -recursive | Verify formatting; fail the pull request when files differ | -check exit code only; -recursive includes modules | Exit code 3 means files need formatting; run without -check to fix |
terraform init -input=false | Download providers and modules, configure the backend | -upgrade (move versions), -reconfigure, -migrate-state | -upgrade can change provider versions; use it deliberately and review the lock file |
terraform init -migrate-state | Copy existing local state into a new backend | -force-copy skips the prompt | Back up the state first; run once, not in a loop |
terraform validate | Check syntax and internal consistency | -json | Needs init first; it does not call Google Cloud, so it cannot find permission errors |
terraform plan -out=tfplan | Compute and save the proposed changes | -input=false, -lock-timeout=60s, -var-file, -target (avoid) | Plan files can contain secrets; never commit or share them |
terraform plan -detailed-exitcode | Drift check: 0 clean, 1 error, 2 changes | -refresh-only for real-world changes only | Many CI runners stop at any non-zero code; capture the code in a variable |
terraform apply tfplan | Apply exactly the saved plan | -input=false, -lock-timeout=60s | Fails with a stale plan error if state changed after the plan; re-plan |
terraform apply -refresh-only | Write real values into state without changing infrastructure | -auto-approve (lab only) | Does not fix drift; the next plan will propose to revert it |
terraform destroy | Delete every resource in state | -auto-approve (lab only), -target (avoid) | Read the plan; data is deleted; never run it against a production state |
terraform output | Print output values | -raw, -json | Sensitive outputs are hidden but are still stored in state |
Terraform: state, import and recovery
| Command | Purpose | Key flags | Gotcha |
|---|---|---|---|
terraform state list | List the addresses that state manages | Optional address filter | An empty list usually means the wrong backend or prefix |
terraform state show ADDRESS | Show stored attributes of one resource | None needed | May print secret values; restrict who can run it on production |
terraform state mv | Rename or move an address in state | -dry-run | Prefer a moved block in code so the change is reviewed |
terraform state rm | Make Terraform forget a resource, without deleting it | -dry-run | The resource keeps running but loses protections; needs a second reviewer |
import { to = … id = … } block | Adopt an existing resource through a reviewed plan | Terraform 1.5 and later | The ID format differs per resource; see the Import section in the provider docs |
terraform import ADDRESS ID | Older CLI form of import | None needed | Changes state immediately, outside review |
terraform plan -generate-config-out=generated.tf | Draft code for import blocks that have no resource block | Output file must not exist | Generated code needs cleanup; check the help for your version |
terraform force-unlock LOCK_ID | Remove a stale state lock | -force skips the prompt | Use only when no run is active; it does not repair state |
terraform providers lock -platform=… | Record checksums for several operating systems | Repeat -platform per platform | Missing platforms cause checksum errors on runners |
terraform show -json tfplan | Plan as JSON for policy checks | Redirect to a file | The JSON can contain sensitive values |
gcloud: bootstrap, state bucket and identity
| Command | Purpose | Key flags | Cost | Gotcha |
|---|---|---|---|---|
gcloud storage buckets create gs://BUCKET_NAME | Create the state bucket | --project, --location, --uniform-bucket-level-access, --public-access-prevention | Low | Names are global; 409 means taken or already yours |
gcloud storage buckets update gs://BUCKET_NAME --versioning | Keep old state generations | --versioning, --no-versioning | Low (old versions use storage) | Add a lifecycle rule to expire old versions in production |
gcloud storage buckets describe gs://BUCKET_NAME | Verify settings | --format="yaml(...)" | Free | Use it as the independent check after apply |
gcloud storage ls -l gs://BUCKET/PREFIX/ | List state and lock objects | --all-versions | Free | A .tflock object means a run holds the lock |
gcloud storage rm --recursive gs://BUCKET_NAME | Delete a bucket and all object versions | --recursive | Free | Irreversible; sandbox state buckets only |
gcloud services enable API --project=PROJECT_ID | Enable an API | Several APIs can be listed | Free to enable | Prefer google_project_service in code for repeatability |
gcloud services list --enabled --project=PROJECT_ID | Check enabled APIs | --filter, --format | Free | The project in the error is the billed project |
gcloud iam service-accounts create NAME | Create a layer service account | --display-name, --project | Free | Name for the layer: sa-tf-networks |
gcloud iam service-accounts add-iam-policy-binding SA_EMAIL | Allow impersonation or federation | --member, --role | Free | Use roles/iam.workloadIdentityUser for federation, Token Creator for human impersonation |
gcloud iam workload-identity-pools create POOL | Create a federation pool | --location=global, --display-name | Free | Deleted pools are soft-deleted for 30 days; the ID is reserved |
gcloud iam workload-identity-pools providers create-oidc PROVIDER | Trust GitHub (or another OIDC issuer) | --issuer-uri, --attribute-mapping, --attribute-condition | Free | Without an attribute condition, any repository can use the provider |
gcloud iam service-accounts keys list --iam-account=SA_EMAIL | Audit for user-managed keys | --managed-by=user | Free | The goal is an empty result for user-managed keys |
gcloud: diagnosis
| Command | Purpose | Key flags | Gotcha |
|---|---|---|---|
gcloud logging read 'protoPayload.status.code=7' --freshness=1h | Find denied calls and their principal | --project, --limit, --format="table(…)" | Data Access logs may be off for some services |
gcloud policy-troubleshoot iam RESOURCE | Explain why a principal has or lacks a permission | --principal-email, --permission | Check the help for your SDK version; it reports allow policies and denies |
gcloud beta terraform vet tfplan.json | Validate a plan against a policy library | --policy-library | Beta command; flags can change |
gcloud projects describe PROJECT_ID | Confirm project, number and parent | --format="value(projectNumber)" | Use the project number in principalSet strings, not the ID |
gcloud auth application-default login | Credentials for Terraform on a workstation | --impersonate-service-account | Not for pipelines; use Workload Identity Federation there |
Environment variables worth knowing
| Variable | Effect | Gotcha |
|---|---|---|
GOOGLE_IMPERSONATE_SERVICE_ACCOUNT | Terraform acts as that service account | Unset it after tests; it silently changes the identity of every run |
TF_LOG=DEBUG | Verbose Terraform and provider logs | Logs can include request details; do not paste them into public tickets |
TF_IN_AUTOMATION=1 | Trims messages meant for humans | Does not replace -input=false |
GOOGLE_PROJECT / GOOGLE_REGION | Defaults for the Google provider | An unexpected default sends resources to the wrong project; prefer explicit variables |
terraform.tfstate or tfplan, never run destroy against a shared state, never use force-unlock without checking running jobs.Capstone lab and final quiz
Capstone lab for Hour 7: a governed Terraform change, from pull request to verified resource
Goal. Run one change through the full landing-zone workflow in a sandbox: a versioned state bucket, a pinned configuration for a labelled project resource set, a keyless pipeline identity, a plan on a pull request, an apply after approval, a drift test, a policy check and a clean teardown. You prove each step with a command and keep the evidence in a short log.
Prerequisites
- A sandbox Google Cloud project (and, if you have one, a sandbox folder in a sandbox organization) that you may freely create and delete resources in. A budget alert is set first. Budgets send alerts and do not cap spend.
- A private sandbox GitHub repository you own, with Actions enabled. No real secrets, no real data.
- Cloud Shell, or a local shell with
gcloud(current release channel) and Terraform 1.x. Check withgcloud versionandterraform version. - Roles on the sandbox project:
roles/storage.admin,roles/iam.serviceAccountAdmin,roles/iam.workloadIdentityPoolAdmin,roles/serviceusage.serviceUsageAdminandroles/resourcemanager.projectIamAdmin. - Variables for this lab:
PROJECT_ID,PROJECT_NUMBER,REGION,GITHUB_ORGandGITHUB_REPO(written asYOUR_ORG/YOUR_REPObelow).
IDs in the expected output are illustrative.
Steps
- Confirm the target and start the evidence log.
gcloud config set project PROJECT_ID gcloud config get-value project export PROJECT_ID=PROJECT_ID export PROJECT_NUMBER=$(gcloud projects describe "$PROJECT_ID" --format="value(projectNumber)") echo "$PROJECT_ID $PROJECT_NUMBER" | tee evidence.txt
Verification. The first command prints the sandbox project ID. Expected output.
PROJECT_ID PROJECT_ID 123456789012
- Enable the APIs.
gcloud services enable storage.googleapis.com serviceusage.googleapis.com iam.googleapis.com iamcredentials.googleapis.com sts.googleapis.com gcloud services list --enabled --filter="name:(storage OR serviceusage OR iam OR iamcredentials OR sts)" --format="value(config.name)"
Verification. The list contains the five APIs. Cost. Free to enable.
- Create the state bucket.
gcloud storage buckets create gs://PROJECT_ID-tfstate-capstone --project=PROJECT_ID --location=REGION --uniform-bucket-level-access --public-access-prevention gcloud storage buckets update gs://PROJECT_ID-tfstate-capstone --versioning gcloud storage buckets describe gs://PROJECT_ID-tfstate-capstone --format="yaml(versioning,uniform_bucket_level_access,public_access_prevention)"
Verification and expected output.
public_access_prevention: enforced uniform_bucket_level_access: true versioning: enabled: true
Cost. Low.
- Write the configuration in your repository under
envs/capstone/. It creates one labelled bucket and one service account, which are the smallest stand-ins for "a project factory output".envs/capstone/versions.tfandbackend.tfterraform { required_version = ">= 1.5" required_providers { google = { source = "hashicorp/google" version = "~> 6.0" } } backend "gcs" { bucket = "PROJECT_ID-tfstate-capstone" prefix = "capstone" } }envs/capstone/main.tfvariable "project_id" { type = string } variable "region" { type = string } locals { labels = { env = "sandbox" owner = "platform" managed_by = "terraform" } } provider "google" { project = var.project_id region = var.region } resource "google_storage_bucket" "app" { name = "${var.project_id}-capstone-app" location = var.region uniform_bucket_level_access = true public_access_prevention = "enforced" force_destroy = true labels = local.labels } resource "google_service_account" "app" { account_id = "sa-capstone-app" display_name = "Capstone application identity" } resource "google_storage_bucket_iam_member" "app_reader" { bucket = google_storage_bucket.app.name role = "roles/storage.objectViewer" member = "serviceAccount:${google_service_account.app.email}" } output "bucket_url" { value = "gs://${google_storage_bucket.app.name}" }envs/capstone/terraform.tfvarsproject_id = "PROJECT_ID" region = "REGION"
Verification. From
envs/capstone:terraform fmt -check -recursiveprints nothing,terraform init -input=falseends withTerraform has been successfully initialized!, andterraform validateprintsSuccess! The configuration is valid.Commit.terraform.lock.hcl; add.terraform/,*.tfstate*andtfplanto.gitignore. - Create the keyless pipeline identity.
gcloud iam service-accounts create sa-tf-capstone --project="$PROJECT_ID" --display-name="Terraform capstone" gcloud projects add-iam-policy-binding "$PROJECT_ID" --member="serviceAccount:sa-tf-capstone@$PROJECT_ID.iam.gserviceaccount.com" --role="roles/storage.admin" gcloud projects add-iam-policy-binding "$PROJECT_ID" --member="serviceAccount:sa-tf-capstone@$PROJECT_ID.iam.gserviceaccount.com" --role="roles/iam.serviceAccountAdmin" gcloud projects add-iam-policy-binding "$PROJECT_ID" --member="serviceAccount:sa-tf-capstone@$PROJECT_ID.iam.gserviceaccount.com" --role="roles/resourcemanager.projectIamAdmin" gcloud iam workload-identity-pools create github --project="$PROJECT_ID" --location=global --display-name="GitHub Actions" gcloud iam workload-identity-pools providers create-oidc github-actions --project="$PROJECT_ID" --location=global --workload-identity-pool=github \ --issuer-uri="https://token.actions.githubusercontent.com" \ --attribute-mapping="google.subject=assertion.sub,attribute.repository=assertion.repository" \ --attribute-condition="assertion.repository == 'YOUR_ORG/YOUR_REPO'" gcloud iam service-accounts add-iam-policy-binding "sa-tf-capstone@$PROJECT_ID.iam.gserviceaccount.com" --project="$PROJECT_ID" \ --role="roles/iam.workloadIdentityUser" \ --member="principalSet://iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/github/attribute.repository/YOUR_ORG/YOUR_REPO"
Verification.
gcloud iam service-accounts get-iam-policy sa-tf-capstone@PROJECT_ID.iam.gserviceaccount.comshows theprincipalSetbinding;gcloud iam service-accounts keys list --iam-account=sa-tf-capstone@PROJECT_ID.iam.gserviceaccount.com --managed-by=userprintsListed 0 items.Cost. Free. In a real layer the roles are narrower and set at the right scope; this sandbox shortcut is acceptable only because the project is disposable. - Add the plan workflow
.github/workflows/plan.yml(Module 5), withon: pull_requestforenvs/capstone/**,permissions: id-token: write, thegoogle-github-actions/authstep with your provider and service account, thenfmt -check,init,validateandplan -out=tfplan. Also addapply.ymlwithon: pushtomain, anenvironment: capstone-applyandapply tfplan. In the repository settings, create the environmentcapstone-applyand add yourself as a required reviewer.Verification. Push a branch with the files and open a pull request. The plan check passes and the log shows
Plan: 3 to add, 0 to change, 0 to destroy.The stepAuthenticate to Google Cloudshows the service account email and no key. - Review, merge and approve. Read the plan (bucket, service account, IAM member), merge the pull request, then approve the
capstone-applydeployment when the apply job waits.Verification. The apply job ends with
Apply complete! Resources: 3 added, 0 changed, 0 destroyed.Apply complete! Resources: 3 added, 0 changed, 0 destroyed. Outputs: bucket_url = "gs://PROJECT_ID-capstone-app"
- Verify from outside Terraform.
gcloud storage buckets describe gs://PROJECT_ID-capstone-app --format="yaml(name,labels,uniform_bucket_level_access)" gcloud iam service-accounts describe sa-capstone-app@PROJECT_ID.iam.gserviceaccount.com --format="value(email)" gcloud storage buckets get-iam-policy gs://PROJECT_ID-capstone-app --format="value(bindings.role)" gcloud storage ls -l gs://PROJECT_ID-tfstate-capstone/capstone/
Expected output. The labels
env,ownerandmanaged_by; the service account email; the roleroles/storage.objectVieweramong the bindings; the objectcapstone/default.tfstatein the state bucket. - Idempotency check. In
envs/capstone, runterraform plan -input=false -detailed-exitcode; echo "exit=$?"(use your own credentials withgcloud auth application-default login, or impersonation).Verification.
No changes. Your infrastructure matches the configuration.andexit=0. - Create drift and detect it.
gcloud storage buckets update gs://PROJECT_ID-capstone-app --update-labels=owner=someone-else terraform plan -input=false -detailed-exitcode; echo "exit=$?"
Verification. The plan shows
~ "owner" = "someone-else" -> "platform",Plan: 0 to add, 1 to change, 0 to destroy.andexit=2. Revert it by applying through a new pull request (orterraform applyin the sandbox), then repeat the plan and confirmexit=0. Write one sentence inevidence.txt: revert or accept, and why. - Add one policy check. Create
policy/deny_public.regothat denies agoogle_storage_bucketwhosepublic_access_preventionis notenforced(the Rego pattern from Module 6), run it againstterraform show -json tfplanwith Conftest if available, then deliberately set the value toinheritedin a branch and show that the check fails with your message. Revert the change.Verification. The good plan passes; the bad plan fails before any apply. If you do not have Conftest, run
terraform validateand describe inevidence.txtwhere this check would run in the pull-request workflow. - Negative identity test. In the provider condition, replace the repository name with a different one (
gcloud iam workload-identity-pools providers update-oidc github-actions …; check--helpfor the flags in your SDK version), re-run the plan job, and confirm it fails at the auth step. Restore the condition and confirm it passes.Verification. The failing run says the credential was rejected; the restored run passes. This proves the pipeline identity is bound to your repository.
Expected result
- A merged pull request whose plan and apply ran without any key file.
- A state object in the versioned state bucket, with at least two generations after the label change.
- A recorded drift event with exit code 2 and a decision.
- A policy check that fails a bad plan before apply.
- An
evidence.txtwith the project, the plan summaries, the exit codes and your decisions.
Cost
Low (usually well under a few USD per day for this lab): two nearly empty buckets, one service account and GitHub runner minutes under your GitHub plan. IAM, Workload Identity and API enablement are free. Check the Billing report for the sandbox project the next day. Budgets send alerts and do not cap spend, so do not leave the lab running.
Cleanup (in this order)
- Destroy the Terraform-managed resources while state still exists.
cd envs/capstone terraform destroy -input=false
Read the plan (Plan: 0 to add, 0 to change, 3 to destroy.) and typeyes. Verification:gcloud storage buckets list --project=PROJECT_ID --format="value(name)"no longer listsPROJECT_ID-capstone-app. - Remove the federation objects and the pipeline service account.
gcloud iam workload-identity-pools providers delete github-actions --project="$PROJECT_ID" --location=global --workload-identity-pool=github gcloud iam workload-identity-pools delete github --project="$PROJECT_ID" --location=global gcloud iam service-accounts delete "sa-tf-capstone@$PROJECT_ID.iam.gserviceaccount.com" --project="$PROJECT_ID"
Pool and provider are soft-deleted for 30 days, so do not reuse the IDs in that period. - Remove the state bucket last (sandbox only; this deletes every object version).
gcloud storage rm --recursive gs://PROJECT_ID-tfstate-capstone
- Delete the sandbox workflows, the environment
capstone-applyand the repository if you created it only for this lab. Removeevidence.txtif it holds anything private. - Final check:
gcloud storage buckets list --project=PROJECT_IDandgcloud iam service-accounts list --project=PROJECT_IDshow nothing from this lab. If the sandbox project was created only for the course, delete it:gcloud projects delete PROJECT_ID(recoverable for a limited period).
gcloud config get-value project before every write and before destroy. Do not run this lab in a project that holds anything you need, and do not point destroy at a state that belongs to a shared environment.Self-check questions
- Which step proved that no key file exists, and which command shows it?
- If the apply job had failed with
403 … API has not been used, which layer would you have checked first? - Where would the policy check run in the workflow, and which control would catch the same mistake if someone used the console?
Knowledge check
Sources and versions
Reference documentation for Hour 7
These are the official and open-source references behind the modules. Pages move, so if a link no longer works, search the title on the same site.
Google Cloud documentation
- Terraform on Google Cloud (overview and guides)
- Get started with Terraform on Google Cloud
- Store Terraform state in a Cloud Storage bucket
- Validate policies for Terraform on Google Cloud
- Enterprise foundations blueprint (security foundations guide)
- Workload Identity Federation
- Workload Identity Federation with deployment pipelines (GitHub, GitLab and others)
- Service account impersonation
- Troubleshoot access in IAM (Policy Troubleshooter)
- Enable and disable services (Service Usage)
- Cloud Build: user-specified service accounts
- Organization Policy overview
- Cloud Storage object versioning
- Uniform bucket-level access
- gcloud CLI reference
Terraform, provider and blueprint repositories
- Terraform Google provider documentation (Terraform Registry)
- hashicorp/terraform-provider-google (changelog and issues)
- Terraform gcs backend
- Terraform import
- terraform plan (including -detailed-exitcode and -refresh-only)
- terraform-google-modules/terraform-example-foundation (bootstrap, org, environments, networks and projects layers)
- terraform-google-modules/terraform-google-project-factory
- terraform-google-modules/terraform-google-bootstrap
- GoogleCloudPlatform/terraform-validator (policy validation tooling)
CI/CD actions and tools
- google-github-actions/auth (Workload Identity Federation for GitHub Actions)
- hashicorp/setup-terraform
- GitHub environments and required reviewers
- Open Policy Agent documentation and Conftest
Tools and versions used in this hour
| Tool | Version used in the course | How to check |
|---|---|---|
| Terraform | 1.x (the labs need 1.5 or later for import blocks) | terraform version |
Google provider (hashicorp/google) | Pin the major version in required_providers (the examples use ~> 6.0) | .terraform.lock.hcl |
| gcloud CLI | Current release channel (not pinned) | gcloud version, gcloud components update |
| GitHub Actions | google-github-actions/auth, hashicorp/setup-terraform and actions/checkout at the major versions shown in the examples | The Releases page of each action |
| Cloud Shell | Managed by Google; includes gcloud and Terraform | terraform version inside Cloud Shell |
gcloud … --help and terraform … -help, test in a lower environment, and have the plan reviewed. IDs and outputs shown in the modules are illustrative, not measurements. Prices are not stated in this course; use the Google Cloud pricing pages and a budget alert.