Migrate State Between Backends
Move Terraform state from local to remote backend (S3, GCS, Azure) safely for team collaboration and disaster recovery.
Prerequisites
- -Terraform installed
- -Remote backend bucket/container created
- -Cloud provider credentials configured
Steps
Back up the current state file
Create a local backup of your state file before making any changes to the backend configuration.
Always keep a backup. If the migration fails, you can restore from this copy.
Add the remote backend configuration
Define the new backend block in your Terraform configuration pointing to the remote storage location.
Use a DynamoDB table for state locking to prevent concurrent modifications.
Initialize with migration flag
Run terraform init with the -migrate-state flag. Terraform detects the backend change and prompts to copy existing state.
Answer 'yes' when prompted. If you answer 'no', your state will not be migrated and you may lose track of managed resources.
Verify state in remote backend
List all resources to confirm the state was migrated correctly and all resources are accounted for.
Run a plan to confirm no changes
Execute a plan to ensure Terraform sees no differences between state and infrastructure after migration.
A clean plan with 0 changes confirms the migration was successful.
Remove the local state file
Delete the local terraform.tfstate now that state lives in the remote backend. Keep the backup for a few days.
Only delete local state after you have confirmed the remote backend is working correctly.
Full Script
FAQ
Discussion
Loading comments...