Writing initial Terraform code to spin up a VPC or a Google Kubernetes Engine (GKE) cluster is only 10% of the Infrastructure-as-Code (IaC) journey. The remaining 90% happens on Day 2 and beyond: protecting sensitive state files from credential leakage, preventing concurrent state corruption across distributed engineering teams, and reconciling infrastructure drift when an on-call engineer makes an emergency firewall change in the Google Cloud Console at 2:00 AM.
Adapted from my technical session at DevFest Kampala 2026, this guide walks through a production-hardened blueprint for managing Terraform state and automating drift remediation on Google Cloud Platform (GCP).
Enterprise State & Automated Drift Detection Architecture
Step 1: Provisioning a CMEK-Encrypted GCS State Backend
A critical truth of Terraform is that terraform.tfstate stores attributes in plain text—including initial database passwords, TLS private keys, and service account tokens. Storing state in a standard bucket without strict access boundaries or Customer-Managed Encryption Keys (CMEK) violates enterprise compliance frameworks.
We begin by provisioning a dedicated Cloud KMS KeyRing and symmetric key, granting the Cloud Storage service agent permission to encrypt and decrypt state objects, and enabling Object Versioning plus Soft Delete retention:
export PROJECT_ID="enterprise-cloud-prod"
export REGION="us-central1"
export STATE_BUCKET="gs://${PROJECT_ID}-tfstate-vault"
export KMS_KEYRING="tfstate-keyring"
export KMS_KEY="tfstate-cmek-key"
# 1. Create Cloud KMS KeyRing and Key with 90-day automatic rotation
gcloud kms keyrings create $KMS_KEYRING --location=$REGION
gcloud kms keys create $KMS_KEY \
--location=$REGION \
--keyring=$KMS_KEYRING \
--purpose=encryption \
--rotation-period="7776000s" \
--next-rotation-time="$(date -u -v+90d +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -u -d '+90 days' +%Y-%m-%dT%H:%M:%SZ)"
# 2. Authorize the GCS Service Agent to use the CMEK key
PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)")
gcloud kms keys add-iam-policy-binding $KMS_KEY \
--location=$REGION \
--keyring=$KMS_KEYRING \
--member="serviceAccount:service-${PROJECT_NUMBER}@gs-project-accounts.iam.gserviceaccount.com" \
--role="roles/cloudkms.cryptoKeyEncrypterDecrypter"
# 3. Create the hardened GCS bucket with versioning and 30-day soft delete
gcloud storage buckets create $STATE_BUCKET \
--location=$REGION \
--uniform-bucket-level-access \
--public-access-prevention \
--default-encryption-key="projects/${PROJECT_ID}/locations/${REGION}/keyRings/${KMS_KEYRING}/cryptoKeys/${KMS_KEY}" \
--soft-delete-duration=30d
gcloud storage buckets update $STATE_BUCKET --versioning
Step 2: Blast-Radius Isolation & Native GCS State Locking
Monolithic state files—where networking, GKE clusters, Cloud SQL, and application IAM live in a single default.tfstate—turn every terraform apply into a high-stakes event. Instead, partition state by lifecycle and blast radius (e.g., 01-network, 02-data-plane, 03-compute-gke) using distinct GCS prefixes.
Google Cloud Storage natively supports atomic object locking via HTTP preconditions (ifGenerationMatch: 0), meaning Terraform automatically creates a .tflock file in your bucket without needing an external database:
terraform {
required_version = ">= 1.9.0"
required_providers {
google = {
source = "hashicorp/google"
version = "~> 6.12.0"
}
}
backend "gcs" {
bucket = "enterprise-cloud-prod-tfstate-vault"
prefix = "env/production/03-compute-gke"
kms_encryption_key = "projects/enterprise-cloud-prod/locations/us-central1/keyRings/tfstate-keyring/cryptoKeys/tfstate-cmek-key"
impersonate_service_account = "tf-orchestrator@enterprise-cloud-prod.iam.gserviceaccount.com"
}
}
Step 3: Automated Drift Detection with Cloud Build & Cloud Scheduler
Infrastructure drift occurs when live GCP resources diverge from the Git-committed HCL—typically due to manual hotfixes via the Cloud Console ("ClickOps"), imperative gcloud scripts, or external controllers modifying labels and firewall rules. Waiting until the next feature deployment to discover drift slows down engineering velocity.
We solve this by running a scheduled drift-detection pipeline in Cloud Build using terraform plan -detailed-exitcode, which returns:
0— Succeeded with zero diff (Infrastructure matches Git state).1— Error occurred during plan evaluation.2— Succeeded, and non-empty diff (drift) was detected.
# cloudbuild-drift.yaml
steps:
- name: 'hashicorp/terraform:1.10'
id: 'detect-drift'
entrypoint: 'sh'
args:
- '-c'
- |
terraform init -input=false
set +e
terraform plan -detailed-exitcode -no-color -out=tfplan > plan_output.txt
EXIT_CODE=$?
set -e
if [ $EXIT_CODE -eq 2 ]; then
echo "⚠️ DRIFT DETECTED in production infrastructure!"
gcloud pubsub topics publish infra-drift-alerts \
--message="Drift detected in ${BUILD_ID}. Review Cloud Build logs." \
--attribute="environment=production,severity=HIGH"
cat plan_output.txt
exit 1
elif [ $EXIT_CODE -ne 0 ]; then
echo "❌ Terraform plan failed with error."
exit $EXIT_CODE
else
echo "✅ Zero infrastructure drift detected."
fi
options:
logging: CLOUD_LOGGING_ONLY
Step 4: Declarative Drift Remediation (`import`, `moved`, and `removed`)
Historically, fixing drift or refactoring modules required imperative CLI state surgery (terraform import or terraform state mv)—commands that bypass peer review and risk corrupting production state if run locally. Modern Terraform (1.5 through 1.10+) provides config-driven declarative blocks that execute cleanly inside your GitOps CI/CD pipeline.
Suppose the security team manually created an emergency Cloud Armor rate-limiting rule during a DDoS incident. Instead of deleting their work or running manual CLI imports, we adopt the live resource declaratively and generate its HCL:
# 1. Declaratively import the emergency Cloud Armor policy via Git PR
import {
to = google_compute_security_policy.edge_waf_policy
id = "projects/enterprise-cloud-prod/global/securityPolicies/emergency-ddos-shield"
}
# 2. Refactoring a module path without destroying & recreating Cloud SQL
moved {
from = google_sql_database_instance.primary_db
to = module.highly_available_sql.google_sql_database_instance.primary
}
# 3. Decommissioning a legacy resource from Terraform state without destroying the underlying GCP disk
removed {
from = google_compute_disk.legacy_archive_volume
lifecycle {
destroy = false
}
}
By running terraform plan -generate-config-out=imported_waf.tf, Terraform inspects the GCP API and writes the exact HCL resource definition for the imported Cloud Armor policy, allowing you to commit it straight into version control.
Step 5: Continuous Health Assertions with `check` Blocks
Resource creation succeeding in the Google Cloud API does not guarantee functional readiness. Unlike postcondition blocks (which halt execution and mark resources as tainted), check blocks validate real-time infrastructure health and surface warnings on every run:
check "verify_gke_gateway_tls_health" {
data "http" "gateway_healthz" {
url = "https://api.macz.tech/healthz"
}
assert {
condition = data.http.gateway_healthz.status_code == 200
error_message = "GKE External Gateway endpoint returned ${data.http.gateway_healthz.status_code} instead of 200 OK!"
}
}
Key Takeaways
True Cloud DevOps maturity means treating Terraform state as a Tier-1 security asset. By combining CMEK-backed Cloud Storage buckets, service account impersonation, scheduled Cloud Build drift detection, and declarative import/moved workflows, platform teams on Google Cloud can eliminate configuration drift while maintaining auditability across every environment.