How to Migrate Terraform State from Local to a Remote Backend

When you first start with Terraform, state is stored locally in terraform.tfstate. As your team grows, you need to migrate to a remote backend for collaboration, security, and state locking.

Why Migrate to a Remote Backend?

  • Enables team collaboration — everyone shares the same state.
  • Prevents concurrent apply conflicts with state locking.
  • Keeps secrets out of your local machine and version control.
  • Enables versioning, encryption at rest, and audit logs.

Step 1: Create the Remote Backend Infrastructure

First, provision the S3 bucket and DynamoDB table for state storage and locking:

# Create S3 bucket (do this manually or with a separate Terraform config)
aws s3api create-bucket \
  --bucket my-terraform-state \
  --region us-east-1

# Enable versioning
aws s3api put-bucket-versioning \
  --bucket my-terraform-state \
  --versioning-configuration Status=Enabled

# Create DynamoDB table for state locking
aws dynamodb create-table \
  --table-name terraform-state-lock \
  --attribute-definitions AttributeName=LockID,AttributeType=S \
  --key-schema AttributeName=LockID,KeyType=HASH \
  --billing-mode PAY_PER_REQUEST

Step 2: Add the Backend Block to Your Config

terraform {
  backend "s3" {
    bucket         = "my-terraform-state"
    key            = "prod/terraform.tfstate"
    region         = "us-east-1"
    encrypt        = true
    dynamodb_table = "terraform-state-lock"
  }
}

Step 3: Run terraform init to Trigger Migration

terraform init

Terraform detects that the backend has changed and prompts:

Do you want to copy existing state to the new backend?
  Pre-existing state was found while migrating the previous backend.
  Enter "yes" to copy this state to the new backend.

Enter a value: yes

Type yes and Terraform automatically copies your local state to the remote backend.

Step 4: Verify the Migration

# Confirm remote state is accessible
terraform state list

# Check the remote state file in S3
aws s3 ls s3://my-terraform-state/prod/

Step 5: Clean Up Local State

After verifying the migration was successful, remove the local state file:

# Keep a backup first
cp terraform.tfstate terraform.tfstate.backup

# Remove local state (remote is now the source of truth)
rm terraform.tfstate
rm terraform.tfstate.backup

Key Takeaway

Migrating to a remote backend is a three-step process: add the backend block, run terraform init, and confirm the migration prompt. Always verify state integrity afterward and enable versioning on your S3 bucket before migrating.

(Visited 1 times, 1 visits today)