terraform move code block - better way to let terraform know you have moved your resources

 Sometimes we refactor our terraform code and move the basic terraform code 

Let's say we have the following code 


# main.tf (Root level)
resource "azurerm_storage_account" "old_storage" {
  name                     = "mystorage2026"
  resource_group_name      = "my-rg"
  location                 = "East US"
  account_tier             = "Standard"
  account_replication_type = "LRS"
}

And then we refactor our code to the following code structure 



The Module Code (modules/storage/main.tf)

Notice that inside the module, I've given the resource a new local name: modular_storage.



resource "azurerm_storage_account" "old_storage" {
  name                     = "mystorage2026jw"
  resource_group_name      = "mytest-kv-rg"
  location                 = "australiaeast"
  account_tier             = "Standard"
  account_replication_type = "LRS"
}

The Module Variables (modules/storage/variables.tf)


variable "storage_name" {
  type = string
}

After we have refactor our code and run terraform apply, pretty sure terraform asking us to create new resources 


Should IAC behave like this?  Why are we adding code block to say "Hey,  terraform I have move - why can't terraform maintain it's own statefile - I indirectly". What if someone deleted the code - i have to go searching for it in git histories.


So we just have to add additiona block "moved" - so fix statefile and let terraform awere.


provider "azurerm" {
  features {}
}

# stage 1
# resource "azurerm_storage_account" "old_storage" {
#   name                     = "mystorage2026jw"
#   resource_group_name      = "mytest-kv-rg"
#   location                 = "australiaeast"
#   account_tier             = "Standard"
#   account_replication_type = "LRS"
# }

# stage 2 refactoring

module "storage_module" {
  source       = "./modules/storage"
  storage_name = "mystorage2026"
}

# # 2. THE MOVE BLOCK
# # This maps the old "address" to the new "modular address"
moved {
  from = azurerm_storage_account.old_storage
  to   = module.storage_module.azurerm_storage_account.old_storage
}


And finally we have the plan that says no changes







Comments

Popular posts from this blog

vllm : Failed to infer device type

android studio kotlin source is null error

gemini cli getting file not defined error