patternbashterraformTip
Terraform modules: structure and calling conventions for reusable infrastructure
Viewed 0 times
modulesmodule sourcereusable infrastructuremodule registrymodule versioningchild module
Error Messages
Problem
Placing all resources in a single flat
main.tf file makes infrastructure difficult to reuse, test, and maintain as it grows. Teams end up copying and pasting HCL across environments, leading to drift between dev and prod.Solution
Extract related resources into child modules with a clear interface (variables, outputs). Publish shared modules to a private registry or reference them via relative paths or git sources.
Module directory structure:
Calling a module:
Module directory structure:
modules/
rds-postgres/
main.tf # resources
variables.tf # input variables
outputs.tf # output values
versions.tf # required_providers
README.mdCalling a module:
module "database" {
source = "./modules/rds-postgres"
# or: source = "git::https://github.com/org/tf-modules.git//rds-postgres?ref=v1.2.0"
identifier = "app-db-${var.environment}"
instance_class = "db.t3.medium"
vpc_id = module.networking.vpc_id
subnet_ids = module.networking.private_subnet_ids
}Why
Modules are the primary unit of reuse in Terraform. They enforce consistent resource configuration across environments and make it easy to upgrade shared infrastructure patterns in one place.
Gotchas
- After changing a module source path or version, run
terraform initto update the local cache - Module outputs must be explicitly declared — callers access them as
module.<name>.<output> - Deep module nesting (modules calling modules) makes plans difficult to read — prefer shallow hierarchies
- Pin module version with
?ref=v1.2.0when using git sources to prevent unexpected upgrades
Context
Managing infrastructure across multiple environments or teams with shared patterns
Revisions (0)
No revisions yet.