Today a quick post about code refactoring and Terraform. Let’s assume that you have an AWS account with several projects in which you use IaC. You created a lot of resources, but decided to clean up the code and move a few S3 buckets to another module. You organize the code, but what to do to keep the resources in AWS and at the same time move them to another module?
As soon as you change the names or move resources to a different place in the code, terraform will want to remove resources and add them again. If your buckets are full of files, you probably don’t want to delete them, but you want to keep them intact.
With the terraform state mv
command, you can make the state change and keep the resources in AWS intact. I recommend making a backup first. You can also do a dry run. You can find an example below:
# backup
terraform state pull > backup.tfstate
# list resources
terraform state list
# mv dry-run
terraform state mv -dry-run \
'module.s3.module.aws_s3_bucket["my-s3-bucket"].bucket_s3.this[0]' 'module.s3.module.aws_s3_bucket["project1-s3-bucket"].bucket_s3.this[0]'
# mv
terraform state mv \
'module.s3.module.aws_s3_bucket["my-s3-bucket"].bucket_s3.this[0]' 'module.s3.module.aws_s3_bucket["project1-s3-bucket"].bucket_s3.this[0]'
terraform state mv [options] SOURCE DESTINATION
When manipulating state, make sure no one else is adding changes between your configuration change and the terraform state mv
command at the time. Otherwise, someone could accidentally create a plan that will destroy the old resources and create a new one.
You can find more about refactoring in my article on dev_to Power of Terraform Code Refactoring.
See the terraform documentation for more information Command: state mv | Terraform | HashiCorp Developer
If you liked the article, let me know and I will try to add some more cool tips about terraform.
.