Published on

Migrating resources across Terraform Remote State

Authors
  • Name
    Twitter

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:

  1. Editing or writing directly to the new state file. (Not recommended)
  2. Using the Terraform mv command
  3. 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

  1. 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
List all resources
  1. Run terraform rm with the resource address to remove resources from the old state file.
terraform state rm ADDRESS...
  1. 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
  1. Voilà! You have successfully migrated a resource to a new state file.

Common Errors

  1. 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.

  1. 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