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.
1. Back Up Your Local State
Section titled “1. Back Up Your Local State”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.
cp terraform.tfstate terraform.tfstate.backupTerraform 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.
2. Initialize the Remote Backend
Section titled “2. Initialize the Remote Backend”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" }}3. Run terraform init
Section titled “3. Run terraform init”Once the remote backend is defined in your configuration, run:
terraform initDuring initialization, Terraform will detect that you’re changing from a local backend to a remote backend. It will prompt you to confirm the migration.
4. Approve the Migration
Section titled “4. Approve 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.
5. Verify the Migration
Section titled “5. Verify the Migration”After migration, you can verify that your state file is stored remotely by running:
terraform state listThis 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 Migration Fails
Section titled “If Migration Fails”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:
-
Check whether the remote backend received the state file. If it did, the migration may have succeeded despite the error. Run
terraform state listto confirm. -
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 -
Remove or comment out the
backendblock in your configuration, then runterraform initto return to local state management. -
Fix the issue that caused the failure (credentials, bucket permissions, network connectivity) and attempt the migration again from step 1.