You must refactor loose resources into a module in a live prod state without recreating anything. How?
AdvancedScenarioModules and Code Structure
Answer
Situation read → The resources already exist; only their addresses change.
What I'd do →
- Create the module with the same resource definitions.
- Add
movedblocks from the root addresses tomodule.x.…. - Run
terraform plan; it must show only "moved", no create/destroy. - Apply, and keep the
movedblocks for a release or two.
moved {
from = aws_security_group.app
to = module.app.aws_security_group.this
}
Why → moved is declarative, reviewable and applies the same way in every environment.
Interview tip → Mention that plan output literally says "has moved to" for each, which is your proof.
More on Modules and Code Structure
When do you turn a block of resources into a module, and when do you leave it alone?BeginnerHow do you consume a community module like `terraform-aws-modules/vpc/aws` responsibly?BeginnerAn ECS service module needs the VPC and subnets created by a network module. How do you wire them together?IntermediateHow would you lay out a repo that deploys the same stack to dev, stage and prod?IntermediateHow do you release a shared module so consumers can upgrade at their own pace?IntermediateA module needs to deploy to a second region. Why does putting a provider block inside the module cause trouble?Advanced