- Published on
Migrating resources across Terraform Remote State
- Authors
- Name
Migrating resources across Terraform Remote State
Many reasons exist for moving resources across Terraform state files. These could include splitting a monolithic state file, moving to a new backend, and refactoring infrastructure for better collaboration among teams. There are several options for migrating these resources, and they can include:
- Editing or writing directly to the new state file. (Not recommended)
- Using the Terraform mv command
- Using the terraform state rm and terraform import.
I will link the existing blog post or article to the first two options and provide more detailed discussion on the third option.
Using the terraform state rm and terraform import in the location
Steps
- List all resources in the current state file and save them in a file.
terraform refresh -no-color -lock=false | sed -E 's/:.*\[id=([^]]*)\]/, \1/' > resources.txt
- Run terraform rm with the resource address to remove resources from the old state file.
terraform state rm ADDRESS...
- Go to the new directory to import the new state. Ensure the backend is pointing to the correct state file. Run Terraform import with the resource address and ID.
terraform import [options] ADDRESS ID
- Voilà! You have successfully migrated a resource to a new state file.
Common Errors
- Resource already managed by terraform
This indicates that the resource has already been imported, exists in the Terraform state, or is part of the Terraform configuration.
- Resource Dependency Issues Before importing resources, it is essential to carefully access the interdependencies among them to understand the order of creation and updates. If a resource depends on each other, use the data source, moved block, remote state file or other alternatives.
Resources
- https://developer.hashicorp.com/terraform/cli/commands/state/rm
- https://developer.hashicorp.com/terraform/cli/commands/import
- https://developer.hashicorp.com/terraform/cli/commands/state/mv
- https://medium.com/@lynnlin827/moving-terraform-resources-states-from-one-remote-state-to-another-c76f8b76a996
- https://technotrampoline.com/articles/renaming-and-moving-things-in-terraform/
- https://developer.hashicorp.com/terraform/language/state/remote-state-data