Skip to content

Migrate State to a Remote Backend

If you’ve been using local state and want to migrate to a remote backend, the process involves a few steps. It’s important to be cautious when migrating state, as improper handling can result in losing or corrupting your state file.

Before making any changes, create a copy of your local state file. If something goes wrong during migration, this backup lets you restore your previous state and try again.

Terminal window
cp terraform.tfstate terraform.tfstate.backup

Terraform also creates a terraform.tfstate.backup file automatically during some operations, but making your own explicit copy ensures you have a known-good snapshot before the migration starts.

Update your terraform block in the configuration to define the remote backend. For example, you could configure the backend as follows:

terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "state/terraform.tfstate"
region = "us-west-2"
}
}

Once the remote backend is defined in your configuration, run:

Terminal window
terraform init

During initialization, Terraform will detect that you’re changing from a local backend to a remote backend. It will prompt you to confirm the migration.

Terraform will ask you to confirm if you want to migrate the state from local to the remote backend. If you confirm, it will upload your current local state file to the remote backend.

After migration, you can verify that your state file is stored remotely by running:

Terminal window
terraform state list

This should return the list of resources from the remote backend. Also, check the remote storage (e.g., S3 bucket) to ensure the state file has been uploaded.

If the migration fails partway through — for example, due to network issues or incorrect backend credentials — your state may be in an inconsistent state. Here is how to recover:

  1. Check whether the remote backend received the state file. If it did, the migration may have succeeded despite the error. Run terraform state list to confirm.

  2. If the remote backend is empty or the state is incomplete, restore your backup by copying it back:

    Terminal window
    cp terraform.tfstate.backup terraform.tfstate
  3. Remove or comment out the backend block in your configuration, then run terraform init to return to local state management.

  4. Fix the issue that caused the failure (credentials, bucket permissions, network connectivity) and attempt the migration again from step 1.