Move resource block to module block without destroying the resource

38 Views Asked by At

I have an EC2 instance resource that I've built in the past using the below resource block:

resource "aws_instance" "this" {
    ...
}

Now I want to migrate it to a module block that I have created.

I've tried to replace the resource block with my module block but in the terraform planning, I see that it intends to replace my instance and I do not want that.

Is there any way I could switch to the module block without terraform recreating my resources?

1

There are 1 best solutions below

2
Matthew Schuchard On BEST ANSWER

You would need to move the address for the resource in the state. Without knowledge of the new address (module declaration and plan both absent from question), the following subcommand executed from the root module will achieve the desired goal:

terraform state mv aws_instance.this module.my_module.aws_instance.this

More information can be found in the documentation.

Alternatively one can also use the moved block with a recent version of terraform:

moved {
  from = aws_instance.this
  to   = module.my_module.aws_instance.this
}