When managing Terraform configurations, it's common to organize resources into modules for better structure and maintainability. However, moving resources between modules or back to the main configuration file, requires careful handling to avoid unnecessary recreation of resources and minimize the downtime.
Please ensure to move the terraform configuration (code) of the particular resource in or out the module while moving the resource address in terraform state file.
This knowledge base provides a structured approach for moving Terraform resources between modules and main configuration files while considering count meta-arguments.
Pre-Requisites:
1. Initial Setup:
Before implementing modules, resources may exist directly in the main configuration file (main.tf).
resource "null_resource" "resource_null" {}
2. Moving Resources to a Module:
When moving resources to a module (terraform_null_module), use terraform state mv to update the state accordingly.
terraform state mv null_resource.resource_null module.terraform_null_module.null_resource.resource_null
After this move, the state reflects the new identifier:
terraform state list
module.terraform_null_module.null_resource.resource_null
Alternatively, a "moved block" can be used to move a resource within the state file:
module "terraform_null_module" {
source = "./modules/terraform_null_module" }
moved {
from = null_resource.resource_null
to = module.terraform_null_module.null_resource.resource_null
}
3. Removing Module Structure:
If the module structure needs to be updated i.e. resources needs to be removed from the module, the resources can be moved back to the main configuration file using below command:
terraform state mv module.terraform_null_module.null_resource.resource_null null_resource.resource_null
Alternatively, "moved block" can also be used as below:
moved {
from = module.terraform_null_module.null_resource.resource_null
to = null_resource.resource_null
}
4. Moving Resources with count Meta-Argument:
When dealing with resources having count meta-arguments, index-based updates are necessary for each instance.
For resources with count specified in the module:
moved {
from = null_resource.resource_null[0]
to = module.terraform_null_module.null_resource.resource_null[0]
}
And for resources with count specified in the main configuration in module block:
moved {
from = null_resource.resource_null[0]
to = module.terraform_null_module[0].null_resource.resource_null
}
5. Moving Back from Module to Main Configuration:
Similarly, moving to modules & moving back from modules requires index-based moves, especially when dealing with resources with count.
moved {
from = module.terraform_null_module[0].null_resource.resource_null
to = null_resource.resource_null[0]
}
Note: Ensure to handle count indexing appropriately based on whether count is specified in the resource or module block.
References:
https://developer.hashicorp.com/terraform/cli/commands/state/mv