A module needs to deploy to a second region. Why does putting a provider block inside the module cause trouble?
AdvancedScenarioModules and Code Structure
Answer
Situation read → Provider blocks inside child modules make the module impossible to use with for_each/count and hard to remove.
What I'd do →
- Remove provider blocks from the module.
- Declare the expected provider names with
configuration_aliases. - Pass providers from the root.
# in module
terraform {
required_providers {
aws = { source = "hashicorp/aws", configuration_aliases = [aws.replica] }
}
}
# in root
module "bucket" {
source = "./modules/replicated-bucket"
providers = { aws = aws, aws.replica = aws.dr }
}
Why → If you delete a module that contains its own provider, Terraform can't destroy its resources because the provider config vanished with it.
Interview tip → "Providers belong in the root."
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?IntermediateTeams complain a "VPC module" has 90 variables and still doesn't do what they need. How do you fix the design?Intermediate