IaC Modules: When and How to Extract Them
Structure reusable OpenTofu/Terraform modules with clean inputs, outputs, and semantic versioning—and know when a module is premature abstraction.
TL;DR
A module is a folder of .tf files that groups cohesive resources behind typed variables.tf inputs and outputs.tf outputs, pinned by a Git tag (?ref=v1.2.0). Don't wrap a single resource just to feel "DRY"—wait until you have a repeatable pattern used across multiple environments or teams.
Why it exists
Copying 150 lines of VPC, subnet, NAT, and route-table HCL into dev/, staging/, and prod/ guarantees drift. Extracting a cohesive pattern into a module lets every environment share the same security defaults while varying only size, CIDR, or tags.
Mental model
Treat a module like a pure function:
- Root module: owns
backend {},provider {}, and concrete environment values. - Child module: declares
required_providers(noprovider {}credentials),variableinputs withvalidationblocks, cohesive resources, andoutputvalues.
Do it
Standard module structure:
modules/app-service/
├── README.md
├── versions.tf # required_version + required_providers
├── variables.tf # typed inputs + validation blocks
├── main.tf # cohesive resources
└── outputs.tf # IDs, endpoints, ARNs needed by callersCalling a versioned Git module and refactoring safely with moved:
# environments/prod/main.tf (not run)
module "api" {
source = "git::https://github.com/acme/infra-modules.git//modules/app-service?ref=v1.4.0"
name = "orders-api"
env = "prod"
replicas = 3
}
# Safe refactor when moving an existing resource into a module
moved {
from = aws_ecs_service.api
to = module.api.aws_ecs_service.this
}Gotchas
- Thin wrapper modules: a module that wraps one
aws_s3_bucketand exposes 25 pass-through variables adds indirection without value. - Mutable branch refs:
?ref=mainmeans tomorrow'stofu applyinprodcan pull breaking module changes. Always pin a tag (?ref=v1.4.0) or commit SHA. - Embedding
provider {}inside child modules: prevents callers from usingcountorfor_eachon the module and locks the module to one region/account. - Deep module nesting: 3+ levels of modules calling modules makes
tofu plandiffs andmovedblocks painful to trace. Keep trees flat (max 1–2 levels).
Production checklist
- Pin every remote module source to an immutable Git tag or commit SHA
- Add
type,description, andvalidationrules on all modulevariableblocks - Keep
provider {}andbackend {}blocks exclusively in root modules - Use
moved {}blocks when renaming resources or extracting modules over live state - Run
tofu fmt -check,tofu validate, andtflintin module CI
Check yourself
Check Yourself
1. You extract an existing aws_sqs_queue.orders resource into module.orders_queue. How do you prevent OpenTofu from destroying and recreating the live queue?
2. Why should a reusable child module declare required_providers in versions.tf instead of a provider {} block?
Sources
Related Notes
Remote State and Locking in OpenTofu / Terraform
Why local tfstate breaks in teams, how to configure S3 or GCS remote backends with state locking, and how OpenTofu encrypts state client-side.
Terraform vs OpenTofu: License, Features, and Choice
Compare HashiCorp Terraform and OpenTofu across license history (BSL vs MPL), feature divergence, compatibility, and which one to pick.