How to rename a resource?

QuestionsQuestions8 SkillsProDec, 19 2025
0140

To rename a resource in Terraform without destroying and recreating the actual infrastructure, you need to perform two specific steps. This ensures both your code and your state file stay in sync.

Here is the process:

1. Update your Configuration Code

Open your main.tf file and change the resource name.

Example:
Change:

resource "local_file" "example" { ... }

To:

resource "local_file" "example_renamed" { ... }

Note: At this point, if you run terraform plan, Terraform will see a "new" resource and want to delete the "old" one.

2. Update the State File

Use the terraform state mv command to tell Terraform that the resource hasn't been deleted, just renamed. The syntax is:
terraform state mv <old_address> <new_address>

In your current environment, run:

terraform state mv local_file.example local_file.example_renamed

Why do we do this?

If you only change the code, Terraform looks at its "memory" (the state file), sees local_file.example, but notices it's missing from your script. Simultaneously, it sees local_file.example_renamed in your script but not in its memory. Therefore, it decides to delete the old one and create a new one.

By using state mv, you update Terraform's memory so it knows the existing resource now has a new name in the code.

Give it a try in the terminal, and then run terraform plan to verify that Terraform reports "No changes"!

0 Comments

no data
Be the first to share your comment!