# Manage Terraform State on Google Cloud Storage(GCS)

It's a best pratice to manage Terraform state on central storage like GCS for GCP.

We need to create a Bucket to store the state files:

$ gsutil mb -p pkslow -l us-west1 -b on gs://pkslow-terraform
Creating gs://pkslow-terraform/...

$ gsutil ls gs://
gs://pkslow-terraform/

Define the backend "gcs" in Terraform code:

terraform {
  backend "gcs" {
    bucket  = "pkslow-terraform"
    prefix  = "state/gcp/pubsub"
  }
}

Initiate the Terraform project, it will help to create folder in the Bucket:

$ terraform init -plugin-dir=${TERRAFORM_PLUGIN}

Apply the change:

$ terraform apply -auto-approve

Check on the GCP Console, the state file is created:

What's more, we can also fetch the data from the remote state:

data "terraform_remote_state" "foo" {
  backend = "gcs"
  config = {
    bucket  = "terraform-state"
    prefix  = "prod"
  }
}

resource "template_file" "bar" {
  template = "${greeting}"

  vars {
    greeting = "${data.terraform_remote_state.foo.greeting}"
  }
}

# Code

Code on GitHub: https://github.com/LarryDpk/pkslow-samples


Reference:

Manage GCP Pubsub with Terraform (opens new window)

Terraform GCS (opens new window)

Last Updated: 8/18/2023, 11:39:36 PM