terraform backend - ghdrako/doc_snipets GitHub Wiki

GCS

  1. Create the bucket you’ll be storing the state in
REGION=us-west1
gsutil mb -p $(gcloud projects list --format="value(project_id)" --filter="yourprojectname") -l $REGION gs://name-of-bucket-to-store-state
  1. Enable object versioning to avoid any corruption with your state file
gsutil versioning set on gs://name-of-bucket-to-store-state
  1. create a backend.tfvars
cho -e "bucket         = \"$(gsutil ls | grep yourprojectname | awk -F '[/:]' '{print $4}')"\" | tee backend.tfvars
echo -e "prefix         = \"terraform/state\"" | tee -a backend.tfvars
  1. Add this block to your terraform code
terraform {
  backend "gcs" {}
}
  1. Use backend
terraform init -backend-config backend.tfvar