Skip to content
Visual explainer 3h 30m to learn 5 steps

Terraform on Google Cloud with remote state and modules

Provision resources with the Google provider, variables and modules, keep state in a locked bucket, and review a plan per environment.

By Invicly Tech, , in Google Cloud Engineering and Services. About 9 minutes to read.

Topic 22 of 32

In short

Terraform describes cloud resources in files and makes the real world match them. It keeps a state file that records what it created. For a team, that state belongs in a locked Cloud Storage bucket, and every change should be a reviewed plan.

Think of it like this: Terraform state is the shopping list's tick marks: without it, Terraform cannot tell which items you already bought.

Explained simply

Terraform lets you write down the cloud resources you want in plain files. You run a command, and Terraform creates or changes things until reality matches the files. This is called infrastructure as code. It is repeatable, reviewable and easy to copy.

To do its job, Terraform keeps a record called state. It says which real resources belong to which parts of your code. If the record is lost, Terraform may try to create things that already exist.

On a laptop, state sits in a local file. That is fine for learning, but not for a team. Two people running Terraform at once could damage each other's work. So teams keep state in a Cloud Storage bucket. The bucket backend locks the state during a run and, with versioning on, keeps older copies.

As the code grows, you group related resources into modules, like functions in a program. Your dev and prod folders can call the same module with different inputs, such as a smaller instance count in dev.

Before you apply, read the plan. It lists what will be added, changed or destroyed. The word destroy deserves a slow second look.

Press Play on a diagram to walk through it one step at a time.

LayersHow a Terraform repo is organised
  1. 1
    environments/prod

    Own backend prefix and variable values

  2. 2
    environments/dev

    Same modules, smaller settings

  3. 3
    modules/

    Reusable blocks such as a Cloud Run service

  4. 4
    Google provider

    Talks to Google Cloud APIs

  5. 5
    Cloud Storage backend

    Holds state, with versioning and locking

FlowA safe Terraform change
  1. 1
    Edit code

    In a branch

  2. 2
    terraform fmt and validate
  3. 3
    terraform plan -out

    Review in the pull request

  4. 4
    Approve
  5. 5
    terraform apply tfplan
  6. 6
    Check the resource

    Console or gcloud

In depth

The Google provider and authentication

The provider block sets the default project and region. For authentication on your laptop, run gcloud auth application-default login so Terraform uses your own credentials. In automation, use a service account through workload identity federation, not a key file. Give the account only the roles it needs. Terraform can enable APIs with google_project_service, which is useful because a new project has most APIs off. Pin the provider version range so a surprise upgrade does not change behaviour.

  • Set project and region in the provider block
  • Use application default credentials locally
  • Use federation in CI, not keys
  • Pin provider versions

Remote state with the gcs backend

Create the bucket first, outside the Terraform that uses it, so there is no chicken-and-egg problem. Turn on object versioning and uniform bucket-level access. The gcs backend takes a lock while a run is active, so a second run waits or fails instead of corrupting state. Restrict who can read the bucket, because state can contain sensitive values. If a lock gets stuck after a crash, terraform force-unlock with the lock id releases it, but check first that nobody is running.

  • Bucket created separately, versioning on
  • Lock is automatic with the gcs backend
  • Limit access to the state bucket
  • force-unlock only after checking
SequenceTwo engineers, one state
Engineer A
Engineer B
State bucket
  1. 1apply: take lock
    Engineer A to State bucket: apply: take lock
  2. 2apply: lock denied
    Engineer B to State bucket: apply: lock denied
  3. 3write new state, release lock
    Engineer A to State bucket: write new state, release lock
  4. 4retry: take lock
    Engineer B to State bucket: retry: take lock
  5. 5state is current
    State bucket to Engineer B: state is current

Modules, environments and reading plans

A module takes variables and returns outputs. Put a Cloud Run service, its service account and its IAM in one module, then call it from dev and prod with different values. Keep a separate state prefix for each environment, so dev changes cannot touch prod. Do not use one state for everything. When you read a plan, look at the summary line first, then any resource marked for replacement or destroy. Save it with terraform plan -out=tfplan and apply that exact file after review.

  • Variables in, outputs out
  • One state per environment
  • Check destroy and replace lines
  • Apply the saved plan file

Learn it in 5 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Configure the Google provider~40m
  2. 2
    Store state in a Cloud Storage backend~40m
  3. 3
    Split code into modules~40m
  4. 4
    Separate dev and prod environments~40m
  5. 5
    Review the plan before apply~40m

Key points

  • The google provider needs a project and a region. Authenticate with application default credentials or a service account, not keys in code.
  • The gcs backend stores state in a bucket and locks it during a run. Turn on object versioning on that bucket so you can recover older state.
  • A module is a folder of Terraform with input variables and outputs. Both dev and prod call the same module with different inputs.
  • Keep one state per environment, using separate backend prefixes or folders, so a dev mistake cannot touch prod.
  • Always read the plan. Save it with terraform plan -out and apply that exact file.

Key terms

Tap a card to flip it. 0/5 known

Examples

hcl
terraform {
  required_providers {
    google = { source = "hashicorp/google" }
  }
  backend "gcs" {
    bucket = "example-tf-state"
    prefix = "orders/dev"
  }
}

provider "google" {
  project = var.project_id
  region  = "us-central1"
}

Provider and remote state. Names are placeholders.

Create a state bucket and a first resource

Prerequisites: Terraform installed, gcloud logged in with application default credentials, a project you can safely test in, and billing on. A bucket costs very little. Steps: create the state bucket with gcloud, run init, plan and apply. Expected evidence: terraform state list shows the resource and the state object appears in the state bucket. Cleanup: terraform destroy, then delete the state bucket.

bash
gcloud storage buckets create gs://example-tf-state --location=us-central1
gcloud storage buckets update gs://example-tf-state --versioning
terraform init
terraform plan -out=tfplan
terraform apply tfplan
terraform state list
gcloud storage ls gs://example-tf-state/orders/dev/
# cleanup
terraform destroy

Same module in dev and prod

A module called cloud_run_service takes a name, an image and a minimum instance count. Dev sets min instances to zero to save money. Prod sets it to two for steady latency. Each folder has its own backend prefix. Expected evidence: terraform plan in environments/dev touches only dev resources. A plan in prod shows prod only. The module code itself is written once.

hcl
# environments/prod/main.tf
module "orders" {
  source        = "../../modules/cloud_run_service"
  name          = "orders"
  image         = var.image
  min_instances = 2
}

# environments/dev/main.tf
module "orders" {
  source        = "../../modules/cloud_run_service"
  name          = "orders-dev"
  image         = var.image
  min_instances = 0
}

Quick reference

  • terraform init sets up the provider and backend
  • terraform plan -out=tfplan, then terraform apply tfplan
  • backend "gcs" { bucket, prefix } stores and locks state
  • Turn on versioning for the state bucket
  • One state prefix per environment (dev, prod)
  • Never commit state files or key files to Git
  • Read destroy and replace lines in the plan twice
  • gcloud auth application-default login for local credentials

Common mistakes

  • Committing the state file to Git. It can hold secrets and breaks when two people change it.
  • Applying without a saved plan, so the change differs from what was reviewed.
  • Sharing one state for dev and prod, so one slip can destroy production.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Why keep state in a Cloud Storage backend for a team?

Question 2

2What is a Terraform module?

Question 3

3Which is the safest way to separate dev and prod?

Question 4

4Terraform's plan shows a database marked for replacement. What do you do?

Question 5

5How should CI authenticate to Google Cloud for Terraform?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a provider block that sets project and region from variables.

  2. Exercise 2medium

    Write a backend block for dev state using the bucket example-tf-state.

  3. Exercise 3hard

    Describe a review process so that nothing reaches prod without a reviewed plan.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Can I lose my state?
Yes if it is only on your laptop. With a versioned Cloud Storage bucket you can restore an earlier copy.
Should state be in Git?
No. It can contain secrets and Git cannot lock it.
Terraform or gcloud?
gcloud is good for quick actions. Terraform is better when you need repeatable, reviewed infrastructure.
What if Terraform says the state is locked?
Someone may be running it. Wait, or check the lock id, confirm nothing is running, and use terraform force-unlock.

Go deeper

ShareXLinkedInWhatsApp