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
After
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.
See also.
- Move resource to module
- Rename resource
- Rename output
- Rename variable