Terraform on GCP

💤0
Lv 10 XP
← 🌐 Google Cloud · Infrastructure as Code

Terraform on GCP

Intermediate ⭐ 80 XP ⏱ 16 min #gcp#terraform#iac

Provision Google Cloud with Terraform's google provider and GCS remote state.

📖Theory

Terraform manages GCP via the google provider. You set a default project and region, and authenticate with Application Default Credentials (gcloud auth application-default login) locally or Workload Identity Federation in CI (no key files).

Store remote state in a Google Cloud Storage bucket — GCS provides object versioning and automatic locking, so a separate lock table isn’t needed (unlike AWS’s S3+DynamoDB). The workflow is the universal initplanapply.

🌍Real-World Example
terraform {
  backend "gcs" {
    bucket = "my-tfstate"
    prefix = "prod"
  }
}

provider "google" {
  project = "my-project"
  region  = "europe-west1"
}

resource "google_storage_bucket" "uploads" {
  name     = "my-app-uploads-12345"
  location = "EU"
}
terraform init && terraform plan && terraform apply
✍️Hands-On Exercise
  1. Configure the google provider with a project and region.
  2. Set up a GCS backend for remote state.
  3. Explain why GCS doesn’t need a separate lock table like AWS does.
  4. Add a resource for a storage bucket and run terraform plan.
🧾Cheat Sheet
ItemDetail
Providerprovider "google" { project, region }
Local authADC (gcloud auth application-default login)
CI authWorkload Identity Federation
Remote statebackend "gcs"
LockingNative to GCS (no lock table)
Workflowinitplanapply
💬Common Interview Questions
Where do you store Terraform state on GCP?

In a Google Cloud Storage bucket using the gcs backend, which provides native object versioning and locking — no separate lock table is required.

How should Terraform authenticate to GCP in CI without key files?

Use Workload Identity Federation so the CI runner exchanges its identity for short-lived GCP credentials — no downloaded service account key to leak.

📚Official Documentation

📝 My notes on this topic

Auto-saves as you type