Facebook-color Created with Sketch. LinkedIn-color Created with Sketch.

---Advertisement---

Terraform State Locking with Google Cloud Storage (GCS) Bucket

by Ravi
|
Facebook
Terraform State Locking with Google Cloud Storage (GCS) Bucket
---Advertisement---

Terraform state files track your infrastructure’s current state, but when multiple team members work simultaneously, state corruption can occur. State locking prevents this by ensuring only one user can modify the state at a time. This guide would explain how to configure Terraform State Locking with Google Cloud Storage (GCS) Bucket.

βœ… What is Terraform state locking?
βœ… Why use GCS for Terraform state?
βœ… Step-by-step setup with GCS bucket
βœ… Troubleshooting common issues

Why Use GCS for Terraform State?

  • πŸ”’ Automatic Locking – Prevents concurrent modifications.
  • 🌍 Remote State Storage – Enables team collaboration.
  • ⚑ Versioning & Encryption – GCS supports object versioning and KMS encryption.
  • πŸ’‘ Cost-Effective – Cheaper than Terraform Cloud for small teams.

Step 1: Set Up a GCS Bucket for Terraform State

Prerequisites

  • Google Cloud account with storage.admin permissions
  • Terraform CLI installed
  • Google Cloud SDK (gcloud) configured

Create a GCS Bucket

# Enable GCS API (if not already enabled)
gcloud services enable storage.googleapis.com

# Create a bucket (globally unique name)
BUCKET_NAME="your-unique-tfstate-bucket"
gsutil mb -p YOUR_PROJECT_ID gs://$BUCKET_NAME

# Enable versioning (optional but recommended)
gsutil versioning set on gs://$BUCKET_NAME

Configure Bucket Permissions

# Grant Terraform service account access
gsutil iam ch serviceAccount:terraform-sa@YOUR_PROJECT_ID.iam.gserviceaccount.com:objectAdmin gs://$BUCKET_NAME

Step 2: Configure Terraform to Use GCS Backend

Add this to your main.tf (or a separate backend.tf):

terraform {
  backend "gcs" {
    bucket = "your-unique-tfstate-bucket"  # Replace with your bucket name
    prefix = "terraform/state"             # Optional folder structure
    credentials = "path/to/service-account-key.json"  # Optional if using ADC
  }
}

Initialize the Backend

terraform init

βœ… Verification:

  • Check your bucket:
  gsutil ls gs://$BUCKET_NAME/terraform/state/default.tflock

How State Locking Works in GCS

  • When terraform apply runs, Terraform creates a default.tflock file.
  • If another user runs apply, they’ll see:
  Error: Error acquiring the state lock
  • The lock is automatically released after apply completes (or fails).

Force-Unlock a Stale Lock

terraform force-unlock LOCK_ID

(Get LOCK_ID from the error message or gsutil cat gs://BUCKET/terraform/state/default.tflock)

Best Practices for GCS State Management

  1. πŸ” Enable Bucket Versioning – Roll back accidental state changes.
  2. 🚫 Restrict Bucket Access – Use IAM roles (roles/storage.objectAdmin).
  3. πŸ“ Use prefix for Multiple States – Organize by project/env (e.g., dev/state, prod/state).
  4. πŸ’Ύ Backup State Regularly – Use gsutil cp or GCS retention policies.

Troubleshooting Common Issues

❌ Error: “Failed to lock state”

  • Fix: Check if another user is running Terraform. If not, manually delete default.tflock:
  gsutil rm gs://$BUCKET_NAME/terraform/state/default.tflock

❌ Error: “Permission denied on storage.buckets.get”

  • Fix: Grant storage.objectAdmin to your service account.

❌ Error: “Bucket not found”

  • Fix: Verify the bucket name and region.

Conclusion

Using GCS for Terraform state + locking ensures:
βœ” Team-safe collaboration
βœ” Prevents state corruption
βœ” Secure, versioned backups

πŸš€ Next Steps:

  • Explore Terraform Cloud for advanced features.
  • Automate state backups with gsutil cron jobs.

Need help? Drop a comment below!

Additional Resources

Ravi

Ravi is a Senior DevOps Engineer with extensive experience in cloud infrastructure, automation, CI/CD pipelines, Kubernetes, Terraform, and Site Reliability Engineering (SRE). Passionate about optimizing deployment workflows, enhancing system scalability, and implementing Infrastructure as Code (IaC), Ravi specialises in cloud-native solutions, monitoring, and security best practices. Always eager to explore new technologies and drive innovation in DevOps

Leave a Comment