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.
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
}
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 first. If that looks good, then run without dry-run.
terraform state mv -dry-run aws_instance.example module.my_instance.aws_instance.example
Update the Terraform state with the new resource name.
terraform state mv aws_instance.example module.my_instance.aws_instance.example
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.