Terraform State: Cloud Storage Remote Backend and Workspaces
Scenario
So far, your `terraform.tfstate` file has lived locally on your laptop. If your hard drive crashes, you lose track of the infrastructure. For teams, you must use a Remote Backend. On Google Cloud, the best practice is the gcs backend (Google Cloud Storage). Once remote state is enabled, you can use Terraform Workspaces to spin up independent environments ("dev", "prod") using the exact same code.
- Manually configure a GCS bucket to hold the state file (usually done out-of-band, not via Terraform).
- Add a backend "gcs" block to your terraform {} config.
- Use the terraform.workspace interpolator inside a resource (e.g. naming a pub/sub topic `topic-${terraform.workspace}`).
- Learn the CLI commands to create and switch workspaces.
Additional Context
State Locking: AWS S3 backends require a DynamoDB table for state locking to prevent two people from applying at the same time. The GCS backend has State Locking built-in natively! No extra DB required.
Workspaces: When using the GCS backend with workspaces, Terraform creates separate folders inside your bucket natively: `env/dev/default.tfstate`, `env/prod/default.tfstate`. This lets you reuse the exact same `.tf` files while pushing to different environments safely.
backend.tf
terraform {
backend "gcs" {
# REPLACE THIS with the name of the bucket you created manually in step 1
bucket = "my-tf-state-bucket-2026"
# The folder inside the bucket where the state file will live
prefix = "terraform/state"
}
}main.tf
variable "project_id" { type = string }
provider "google" {
project = var.project_id
}
# The terraform.workspace variable is automatically set by the CLI!
# If you are in the "dev" workspace, this topic becomes "events-dev".
resource "google_pubsub_topic" "environment_topic" {
name = "events-${terraform.workspace}"
labels = {
env = terraform.workspace
}
}Workflow Commands
# 1. Manually create the state bucket ONCE using gcloud
# (Buckets for state should have versioning enabled!)
# gcloud storage buckets create gs://my-tf-state-bucket-2026 --location=us-central1
# gcloud storage buckets update gs://my-tf-state-bucket-2026 --versioning
# 2. Initialise the backend
terraform init
# 3. Create a dev workspace and apply
terraform workspace new dev
terraform apply -var="project_id=my-gcp-project-123"
# 4. Create a prod workspace and apply (creates a totally separate Pub/Sub topic)
terraform workspace new prod
terraform apply -var="project_id=my-gcp-project-123"
# 5. List workspaces
terraform workspace list
# 6. Destroy both cleanly
terraform destroy -var="project_id=my-gcp-project-123"
terraform workspace select dev
terraform destroy -var="project_id=my-gcp-project-123"Successfully configured the backend "gcs"! Terraform will automatically use this backend unless the backend configuration changes. * default * dev prod Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

