Extract Module
Procedure
Extracting a module, let’s call it M, from a config C.
Start with a list of resource and/or data blocks that you’d like to extract.
- Create module folder with a
main.tf
,variables.tf
,outputs.tf
- Include the new empty module from config C with a
module
block - Move the extracted elements from C to M’s
main.tf
- Add
moved
blocks to prevent state changes - For each reference in M to elements in C
- Add a variable to M’s
variables.tf
- Move the expression to an attribute in C’s module include
- Replace the expression in M with a reference to the variable
- Add a variable to M’s
- For each reference in C to elements in M
- Add it as an output to M’s
outputs.tf
- Change the reference in C to use the module’s output.
- Add it as an output to M’s
- Verify Empty Plan
Automation
See tfrefactor.
tfrefactor extract -t ../mymodule my_resource.a my_resource.b
Source code
Before
# C/main.yml
locals {
a_local = "local_val"
}
resource "my_resource" "a" {
}
resource "my_resource" "b" {
a_val = local.a_local
}
resource "something" "else" {
attribute = my_resource.a.attr
}
After
# M/main.tf
resource "my_resource" "a" {
}
resource "my_resource" "b" {
a_val = vaar.b_a_val
}
# M/variables
variable "b_a_val" {
}
# M/outputs.tf
output "a_attr" {
value = my_resource.a.attr
}
# C/main.tf
locals {
a_local = "local_val"
}
resource "something" "else" {
attribute = module.m.a_attr
}
module "m" {
source = "../M"
}
moved {
from my_resource.a
to module.m.my_resource.a
}
moved {
from my_resource.b
to module.m.my_resource.b
}
State operations
If not using moved blocks introduced in Terraform 1.1, a state mv
operation must be used to avoid destroying and recreating resources.
terraform state mv my_resource.a module.m.my_resource.a
terraform state mv my_resource.b module.m.my_resource.b
See also.
- Move resource to module
- Rename resource
- Rename output
- Rename variable