Designing Clean, Reusable Modules
The roadmap asks for "reusable, clean modules". Calling a module is easy; designing one that five teams can use for three years without forking it is the real skill. This lesson is a checklist with one worked example.
The standard layout
modules/postgres/
├── README.md # what it creates, an example call, inputs/outputs (terraform-docs generates the tables)
├── versions.tf # required_version, required_providers (no provider blocks)
├── variables.tf # every input: type, description, validation, sensible default or none
├── main.tf # resources
├── outputs.tf # every value a caller could need, with descriptions
├── examples/
│ └── basic/main.tf # a runnable call, also used by tests
└── tests/
└── defaults.tftest.hclDesign rules
- One purpose, the right size. "A PostgreSQL database with its subnet group, parameter group and security group" is a good module. "Our whole platform" is a root configuration. "One S3 bucket with the same three arguments" adds a layer and no value.
- Small, typed, documented interface. Every variable has a
typeand adescription; prefer oneobjectwithoptional()fields over fifteen loose variables; validate what you can. - Secure, boring defaults. Encryption on, public access off, deletion protection on in the defaults; callers opt out explicitly.
- Expose, don't hide. Output ids, ARNs, names and security group ids, even if you don't need them today. A missing output forces callers to look resources up by name or fork the module.
- No provider configuration, no hard-coded region or account. Use
data "aws_region"/aws_caller_identitywhen needed. - Let callers extend. Accept
tagsand merge them; accept extra security group ids or policy statements rather than predicting every rule. - Avoid unnecessary conditionals. Every
count = var.create_x ? 1 : 0doubles the cases to test. Add flags when callers really need them. - Version it (Module Sources) and treat input/output changes as API changes: a renamed variable is a breaking change (a major version), a new optional variable is not.
A worked interface
mkdir -p proj/modules/naming && cd proj
cat > modules/naming/versions.tf <<'HCL'
terraform {
required_version = ">= 1.6"
}
HCL
cat > modules/naming/variables.tf <<'HCL'
variable "context" {
description = "Who owns the resources and where they run."
type = object({
project = string
environment = string
team = string
cost_center = optional(string, "shared")
})
validation {
condition = contains(["dev", "staging", "prod"], var.context.environment)
error_message = "context.environment must be dev, staging or prod."
}
validation {
condition = can(regex("^[a-z][a-z0-9-]{1,20}quot;, var.context.project))
error_message = "context.project must be lowercase letters, digits and dashes (2-21 chars)."
}
}
variable "extra_tags" {
description = "Tags merged over the standard ones."
type = map(string)
default = {}
nullable = false
}
HCL
cat > modules/naming/outputs.tf <<'HCL'
locals {
prefix = "${var.context.project}-${var.context.environment}"
}
output "prefix" {
description = "Name prefix for every resource, e.g. linkly-prod."
value = local.prefix
}
output "tags" {
description = "Standard tags plus extra_tags."
value = merge({
Project = var.context.project
Environment = var.context.environment
Team = var.context.team
CostCenter = var.context.cost_center
ManagedBy = "opentofu"
}, var.extra_tags)
}
HCL
cat > main.tf <<'HCL'
variable "env" {
type = string
default = "prod"
}
module "naming" {
source = "./modules/naming"
context = { project = "linkly", environment = var.env, team = "platform" }
extra_tags = null # nullable = false: null means "use the default"
}
output "prefix" {
value = module.naming.prefix
}
output "tags" {
value = module.naming.tags
}
HCL
tofu init >/dev/null
tofu apply -auto-approve | sed -n '/^Outputs:/,$p'
echo "--- a caller passing a wrong environment"
tofu plan -var env=production 2>&1 | grep -E 'Error|must be'Outputs:
prefix = "linkly-prod"
tags = {
"CostCenter" = "shared"
"Environment" = "prod"
"ManagedBy" = "opentofu"
"Project" = "linkly"
"Team" = "platform"
}
--- a caller passing a wrong environment
Error: Invalid value for variable
context.environment must be dev, staging or prod.
Points to notice:
- One
contextobject instead of four variables;cost_centeris optional with a default, so the caller didn't set it. nullable = falsemakes an explicitnullfall back to the default ({}), so the module never has to handlenull.- Validation errors point at the caller's mistake with a message in the module's words, before anything is planned.
- Callers use
module.naming.tagson every resource, or set them once as the AWS provider'sdefault_tags(The AWS Provider).
Composition over deep nesting
Prefer root configurations that compose several flat modules, passing outputs from one to the next:
module "network" {
source = "../modules/network"
cidr = "10.20.0.0/16"
}
module "db" {
source = "../modules/postgres"
vpc_id = module.network.vpc_id
subnet_ids = module.network.private_subnet_ids
}over a module that internally calls a module that calls a module. Deep trees are hard to read, hard to test, and make every caller inherit decisions they can't change. The Mini Project builds exactly this composition.
Test yourself
Which change to a published module is a breaking (major) change?
- Adding an optional variable with a default
- Adding a new output
- Renaming an existing input variable
- Improving the README
What does nullable = false on a variable with a default do when the caller passes null?
- Raises an error
- Uses the default value
- Passes null into the module
- Removes the variable
Why should modules output ids and ARNs even if nobody uses them yet?
- Outputs make applies faster
- Callers will need them later; without outputs they must fork the module or look resources up by name
- The registry requires five outputs
- To store them in state