Question

Difficulty: EasyImplementing Infrastructure as Code using Terraform and Deployment Manager

A DevOps engineer needs to migrate an existing local Terraform state file to a Google Cloud Storage (GCS) remote backend for shared team access. What is the correct sequence of steps to migrate the local Terraform state to the GCS remote backend?

  1. 1Create a Google Cloud Storage (GCS) bucket with object versioning enabled.
  2. 2Define the GCS backend configuration block in the Terraform code.
  3. 3Run terraform init to copy local state to the newly configured GCS backend.
  4. 4Confirm state migration success and safely clean up local terraform.tfstate files.

Answer

The correct sequence begins with creating the GCS storage bucket with versioning, followed by declaring the GCS backend in the Terraform code, executing terraform init to migrate state, and finally confirming successful migration before cleaning up local state files.
The GCS bucket must be created first because Terraform requires an existing bucket to initialize its remote state. Once the bucket exists, the backend configuration block is added to code. Running terraform init detects the new backend configuration and performs the migration from local disk to GCS. Finally, verification and cleanup ensure all team members use the single remote source of truth.

Step-by-Step Solution

1
Provision the destination storage bucket in Google Cloud
A secure GCS bucket with versioning enabled is ready to accept state files
Terraform cannot automatically create the remote backend bucket during backend initialization if it does not exist
2
Add the backend backend 'gcs' block to main.tf or provider configuration
Terraform configuration is updated with remote state directives
Terraform requires the explicit bucket name and prefix to connect to the remote backend
3
Execute terraform init
Terraform detects the backend change and transfers state from local disk to GCS
The initialization command performs the state migration process interactively or automatically
4
Verify remote state in GCS and remove local state files
Single source of truth is established in remote storage without duplicate local state
Removing redundant local state files prevents accidental state drift and local execution

Key Concept

Terraform GCS Remote Backend State Migration Workflow
Rate this question