Skip to content

Instantly share code, notes, and snippets.

@todgru
Last active June 6, 2023 21:35
Show Gist options
  • Save todgru/f5c79fa2fdc4bacd56e48df19df278a1 to your computer and use it in GitHub Desktop.
Save todgru/f5c79fa2fdc4bacd56e48df19df278a1 to your computer and use it in GitHub Desktop.
Terraform, move/rename resource to module, AWS

Moving/Renaming Terraform Resources

We have several resources manually created using the AWS Console. I want to manage these resources with Terraform. Originally, I had imported these resources into the Terraform state using individual files. Instead, I should have used modules. I tried moving my files into modules and then using the module to refer to the resource, but the namespace was incorrect. Applying changes at this point would have destroyed and recreated the resources, which is unnecessary.

This is how I moved the resources within the state. This should work for any resource listed in the Terraform state.

Setup the modules

Copy over any resouces declarations to the module format. I didn't rename anything, but I think it is possible at this point.

old resource definition:

resource aws_instance example {
  ...
}

new module defintion:

module my_instance {
  source = modules/instance.tf
}

List Existing Resources in the State

terraform state list

This will list all the resources in the state file. find the names of the resources to move.

example from the docs:

aws_instance.example
module.example
module.example.module.child
module.example.aws_instance.example

Dry Run the Move

Dry run first. If that looks good, then run without dry-run.

terraform state mv -dry-run aws_instance.example module.my_instance.aws_instance.example

Move the Resource

Update the Terraform state with the new resource name.

terraform state mv aws_instance.example module.my_instance.aws_instance.example

Validate the Result

Finally, run plan on the new resource name.

terraform plan -target module.my_instance.aws_instance.example

Output:

No changes. Your infrastructure matches the configuration.

That should be all there is to it. Back to work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment