Interview Prep/Terraform/Modules and Code Structure

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 →

  1. Remove provider blocks from the module.
  2. Declare the expected provider names with configuration_aliases.
  3. 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."

All Terraform questions Roadmap: Terraform

More on Modules and Code Structure