Friday, September 6, 2024

Terraform: How to migrate from old to new state file

 

When you are in production. One of the things you are gonna ask to yourself is how to avoid updating too soon the existing state file in which you might make mistake.

You could create backups but then again, we want to have an extra step to prevent doing restoring the existing state file due to wrong migration.


One use case will be one of our cloud resources will be manage by another team with their own terraform repository


Scenario:

Terraform state A (existing): has the following resource that you want to migrate to Terraform state B (new).

* aws_iam_role_policy_attachment.service_a


Step 1: Pull state file from each terraform repo


Terraform state A (existing):

cd {{ repo-a }}
terraform state pull > $HOME/backup.tfstate
cp $HOME/backup.tfstate $HOME/current.tfstate


Terraform state B (new):

cd {{ repo-b }}
terraform state pull > $HOME/destination.tfstate


Step 2: Migrate resource to new terraform state file


terraform state mv -state=$HOME/current.tfstate -state-out=$HOME/destination.tfstate aws_iam_role_policy_attachment.service_a aws_iam_role_policy_attachment.service_a 

Step 3: Push new state file 

cd {{ repo-b }}
terraform state push $HOME/destination.tfstate


You still have your backup and resource is already migrated and your original terraform repo is still untouched nice!!


Step 4: Validate new terraform repo. Just do a terraform plan. review if output meets your expectation otherwise you need to revisit your step if you did something wrong.

cd {{ repo-b }}
terraform plan

Step 5: Remove resource from old repo
cd {{ repo-a }}
terraform state rm aws_iam_role_policy_attachment.service_a 


Congrats, your done

No comments:

Post a Comment

F# as a scripting language

  If you read on  F# Interactive (dotnet) Reference - .NET | Microsoft Learn , F# language has an official interactive/interpreter support f...