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" "modular_storage" {
  name                     = var.storage_name
  resource_group_name      = "my-rg"
  location                 = "East US"
  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, we will let terraform knows - 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"

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


# 1. Call the new module
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.modular_storage
}









Comments

Popular posts from this blog

vllm : Failed to infer device type

NodeJS: Error: spawn EINVAL in window for node version 20.20 and 18.20

android studio kotlin source is null error