Search code examples
amazon-ec2terraformterraform-provider-awsterraform-modulesterraform-aws-modules

Move resource block to module block without destroying the resource


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?


Solution

  • 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
    }