Question

Difficulty: MediumDeploying Infrastructure using Deployment Manager or Terraform

A Cloud Engineer has a local Terraform configuration managing Google Cloud infrastructure. The engineer wants to migrate the existing local state file (`terraform.tfstate`) to a remote Google Cloud Storage (GCS) backend for team collaboration and state locking. What is the correct sequence of steps to complete this state migration?

  1. 1Create a Cloud Storage bucket in Google Cloud with object versioning enabled.
  2. 2Add a `backend "gcs"` configuration block specifying the bucket name inside the `terraform {}` settings block.
  3. 3Run the `terraform init` command in the working directory.
  4. 4Type `yes` at the terminal prompt to copy the existing local state to the new GCS backend.

Answer

The correct sequence requires creating the Cloud Storage bucket with object versioning first, adding the `backend "gcs"` block to the Terraform configuration, running `terraform init` to initialize the backend, and confirming the prompt by typing `yes` to transfer the local state file to the remote bucket.
Migrating a local Terraform state file to a GCS remote backend follows a strict dependency order: the target Cloud Storage bucket must be created first in GCP because Terraform initialization does not provision the backend bucket automatically. Next, the `backend "gcs"` code block must be declared in the Terraform configuration. Executing `terraform init` causes Terraform to detect the new backend configuration and prompt the user to transfer the state file. Finally, typing `yes` confirms the copy action and migrates the local state file to Cloud Storage.

Step-by-Step Solution

1
Provision a Google Cloud Storage bucket with object versioning enabled.
A secure destination bucket is created to hold the remote state.
Terraform cannot automatically create the state bucket during backend initialization; it must already exist in GCP.
2
Define the `backend "gcs"` configuration block inside the `terraform` block in the HCL file.
The Terraform code now references the remote GCS bucket destination.
Terraform needs explicit backend attributes (such as `bucket` and `prefix`) to determine where state data belongs.
3
Execute `terraform init` in the terminal.
Terraform parses the backend change and initiates the state migration routine.
The initialization command recognizes that the backend changed from local to GCS and triggers state copying.
4
Approve the state migration prompt by typing `yes`.
The local state data is uploaded to Cloud Storage, and local state file references are updated.
User confirmation ensures that existing infrastructure state is safely copied to the remote backend without data loss.

Key Concept

Terraform Remote Backend Migration to Cloud Storage (GCS)
Rate this question