LarryDpk
发布于 2021-11-14 / 2342 阅读
0

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

Terraform GCS