TExcelTAD
Home › Infrastructure as Code: Terraform & OpenTofu › Designing Clean, Reusable Modules

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.hcl

Design rules

  1. 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.
  2. Small, typed, documented interface. Every variable has a type and a description; prefer one object with optional() fields over fifteen loose variables; validate what you can.
  3. Secure, boring defaults. Encryption on, public access off, deletion protection on in the defaults; callers opt out explicitly.
  4. 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.
  5. No provider configuration, no hard-coded region or account. Use data "aws_region"/aws_caller_identity when needed.
  6. Let callers extend. Accept tags and merge them; accept extra security group ids or policy statements rather than predicting every rule.
  7. Avoid unnecessary conditionals. Every count = var.create_x ? 1 : 0 doubles the cases to test. Add flags when callers really need them.
  8. 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

bash · try it yourself
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 context object instead of four variables; cost_center is optional with a default, so the caller didn't set it.
  • nullable = false makes an explicit null fall back to the default ({}), so the module never has to handle null.
  • Validation errors point at the caller's mistake with a message in the module's words, before anything is planned.
  • Callers use module.naming.tags on every resource, or set them once as the AWS provider's default_tags (The AWS Provider).

Composition over deep nesting

Prefer root configurations that compose several flat modules, passing outputs from one to the next:

hcl
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?

  1. Adding an optional variable with a default
  2. Adding a new output
  3. Renaming an existing input variable
  4. Improving the README

What does nullable = false on a variable with a default do when the caller passes null?

  1. Raises an error
  2. Uses the default value
  3. Passes null into the module
  4. Removes the variable

Why should modules output ids and ARNs even if nobody uses them yet?

  1. Outputs make applies faster
  2. Callers will need them later; without outputs they must fork the module or look resources up by name
  3. The registry requires five outputs
  4. To store them in state