2022-11-10

Terraform State Move

Terraform State Move Command

The terraform state mv command is a tool in the Terraform ecosystem designed to manage the state of your resources. It is primarily used to refactor or manipulate the Terraform state, aligning it with changes made in the configuration files.

This command is typically utilized when the logical structure of your infrastructure in the Terraform files has been updated. For example, you might want to rename or restructure your resources or modules, move resources from one module to another, or even shift resources between different Terraform states. In such cases, running a standard terraform apply might end up deleting and recreating resources, which could be destructive and is generally not desired. The terraform state mv comes to the rescue in these scenarios, allowing you to safely move state items without affecting the real resources they represent.

Syntax of Terraform State Move

The terraform state mv command comes with a straightforward syntax. It requires at least two arguments: the source address and the destination address. Here is the basic structure of the command:

bash
$ terraform state mv [options] SOURCE DESTINATION

Both SOURCE and DESTINATION refer to the addresses of the items in your Terraform state. These addresses can refer to a resource or a module. For example, if you have a resource aws_instance named example, the address could be aws_instance.example.

Consider this example where we move a resource within the same module:

bash
$ terraform state mv aws_instance.old aws_instance.new

In this command, we are renaming aws_instance.old to aws_instance.new.

Here is another example where we move a resource from one module to another:

bash
$ terraform state mv module.old_module.aws_instance.example module.new_module.aws_instance.example

In this command, module.old_module.aws_instance.example is the address of the current instance, and module.new_module.aws_instance.example is the address where the instance should be after the command runs.

Ryusei Kakujo

researchgatelinkedingithub

Focusing on data science for mobility

Bench Press 100kg!