Question

Difficulty: MediumDeploying Infrastructure using Deployment Manager or Terraform

A Cloud Engineer needs to migrate an existing local Terraform state file to a Google Cloud Storage (GCS) remote backend to allow team collaboration and state locking. What is the correct sequence of steps to safely execute this backend migration?

  1. 1Create a Google Cloud Storage bucket with object versioning enabled to securely store the state file.
  2. 2Add a backend "gcs" configuration block to the root Terraform module targeting the newly created bucket.
  3. 3Run the command `terraform init` to initialize the configuration and trigger the backend migration process.
  4. 4Confirm the state copy prompt when prompted by the CLI to complete the migration.

Answer

The correct sequence starts with creating the GCS storage bucket, adding the backend block to the HCL configuration, running terraform init, and confirming the state migration prompt.
To migrate state securely to GCS, the target GCS bucket must first exist. Next, the backend "gcs" configuration block is defined in HCL code. Running `terraform init` detects the new backend configuration and initiates the migration. Finally, confirming the migration prompt copies the existing local state file to the remote GCS bucket.

Step-by-Step Solution

1
Provision the GCS bucket
A destination storage location is ready to accept the Terraform state file.
Terraform cannot automatically create the GCS bucket specified in its backend block during initialization.
2
Configure the GCS backend in HCL
The Terraform code defines the remote backend location.
Terraform needs the backend provider block configured in code before it can change state storage locations.
3
Execute terraform init
Terraform detects the backend change from local to GCS.
The init command reconfigures working directory backends and initiates the state copy workflow.
4
Approve the state migration prompt
Local state is uploaded to the GCS bucket and local state file is updated.
Terraform asks for explicit user confirmation before transferring existing local state to remote storage.

Key Concept

Migrating Terraform Local State to GCS Remote Backend
Estimated Time:1m 0s
Rate this question