Terraform Modules: Design Patterns, Versioning and Registry Publishing

Terraform modules are how we stop copy-pasting infrastructure code and start treating it like software. In my experience, the difference between a team that struggles with Terraform and one that ships infrastructure reliably often comes down to whether their modules have a clear contract. A well-designed module hides complexity, exposes only what callers need to change, and can be versioned and shared safely across environments and teams. This article covers how I approach module design, composition, versioning, and publishing to a registry, based on patterns that have held up across dozens of AWS and Azure estates. If you are writing HCL beyond a single root configuration, these practices will help you keep your Terraform Documentation aligned and your infrastructure code maintainable. For broader context on how modules fit into remote state and collaboration, see Terraform State Management: Remote Backends, Locking and State Migration.

The Contract-First Anatomy of a Production-Grade Terraform Module

I design modules from the interface inward. Before writing any resources, I define what the module consumes and what it guarantees to produce. That contract is expressed entirely through variables and outputs. If those are vague, the module will be painful to reuse. A good module behaves like a function: predictable inputs, validated types, sensible defaults, and outputs that downstream modules can actually consume without reaching into its internal resources.

In practice, this means being opinionated about required versus optional inputs. I keep required variables to a minimum: typically naming, environment, network identifiers, and anything that has no safe default. Everything else gets a default that reflects production-safe behavior. For example, an S3 module should default to private ACL, enable versioning and encryption, and block public access unless explicitly overridden. Callers who want a less secure configuration should have to opt into it consciously, not by accident.

Variables, Outputs and the Public Interface

Variable definitions should encode the contract with types, descriptions, and validation. Type constraints like object({...}) or map(string) catch errors early during terraform plan rather than after a resource fails to create. Validation blocks let you enforce naming conventions or allowed values before any API call. I also use nullable variables strategically; a null default that triggers a dynamic block or a conditional resource is often cleaner than a boolean flag.

Outputs deserve the same care. Expose IDs, ARNs, and endpoints that callers will need for wiring, and add descriptions that explain when an output might be null. I've found that adding a single output for the full resource object (where appropriate) saves callers from requesting ten new outputs over the next six months. Just be deliberate about marking sensitive outputs and avoiding exposure of secrets.

# variables.tf - contract for a reusable VPC module
variable "name" {
  description = "Name prefix for all VPC resources. Must be DNS-compatible."
  type        = string
  validation {
    condition     = can(regex("^[a-z0-9-]{3,32}$", var.name))
    error_message = "Name must be 3-32 characters, lowercase alphanumeric and hyphens only."
  }
}

variable "cidr_block" {
  description = "Primary CIDR for the VPC."
  type        = string
  validation {
    condition     = can(cidrhost(var.cidr_block, 0))
    error_message = "Must be a valid IPv4 CIDR block."
  }
}

variable "az_count" {
  description = "Number of AZs to span. Defaults to 3 for HA."
  type        = number
  default     = 3
}

variable "enable_nat_gateway" {
  description = "Provision NAT gateways for private subnets."
  type        = bool
  default     = true
}

# outputs.tf
output "vpc_id" {
  description = "The ID of the VPC."
  value       = aws_vpc.this.id
}

output "private_subnet_ids" {
  description = "List of private subnet IDs across AZs."
  value       = aws_subnet.private[*].id
}

File Layout That Scales Beyond a Single Module

A consistent layout reduces cognitive load. My standard module structure is main.tf, variables.tf, outputs.tf, versions.tf, and optionally locals.tf and README.md. I keep main.tf focused on resources and data sources, move complex transformations to locals.tf, and pin provider and Terraform version constraints in versions.tf. Avoid putting multiple concerns in one module; if your module creates a VPC, EKS cluster, and RDS instance, it is not a module, it is a stack. Split it.

Documentation lives alongside the code. A root README.md generated with terraform-docs that lists inputs, outputs, requirements, and usage examples pays for itself immediately. In my experience, modules without examples are rarely adopted correctly; include at least one minimal example and one production-like example under an examples/ directory. That directory also doubles as your integration test fixture.

Composition Patterns: Wrapping, Facades and Nested Module Architectures

Modules compose. How you compose determines whether your platform team can evolve infrastructure without breaking every downstream consumer. I generally see three useful patterns: wrapper modules, facade modules, and nested child modules.

A wrapper module adds opinionated defaults and policy around a single upstream resource or public module. For instance, wrapping the community terraform-aws-vpc module to enforce your tagging, flow logging, and subnet naming standards. A facade module aggregates several low-level modules behind one simpler interface, for example an app-platform module that provisions an ALB, ECS service, log group, and autoscaling policy together. Nested child modules are internal building blocks within a module, used to repeat a pattern like creating N identical subnets without duplicating code.

Thin Wrapper vs Heavy Abstraction

The most common mistake I see is building heavy abstractions too early. If your wrapper simply passes 40 variables straight through to the underlying resource with no added value, you have added indirection without benefit. I've found that a thin wrapper that sets 3-4 organization-wide defaults, adds mandatory tags, and validates inputs is far more durable than a framework that tries to expose every possible feature as a variable.

Conversely, a facade is justified when the components are always deployed together and have coupling. A web service that always needs a service discovery namespace, IAM role, and CloudWatch alarms is a good facade candidate. The test for whether a facade is appropriate is whether you would ever deploy its parts independently. If the answer is frequently yes, keep them as separate modules and compose at the root level instead.

When to Nest Modules and When Not To

Nesting is powerful but increases the distance between caller input and resource creation, which makes debugging harder. I nest modules when I need to encapsulate repetition or isolate a complex conditional. For example, creating per-AZ NAT gateways and route tables is cleaner as a nested modules/nat-gateway that is called with for_each over AZs. Avoid nesting more than two levels deep; beyond that, plan output becomes hard to trace and state addresses get unwieldy.

Root configurations should remain explicit about dependencies. Use outputs from one module as inputs to another rather than relying on implicit data source lookups across modules. This keeps the dependency graph visible in code and prevents hidden coupling that breaks during refactoring. If you are comparing composition tools more broadly, Pulumi vs Terraform: Infrastructure as Real Code vs Configuration lays out how these patterns differ when you switch languages.

# Root composition: explicit wiring between modules
module "vpc" {
  source   = "./modules/vpc"
  name       = "prod-network"
  cidr_block = "10.0.0.0/16"
}

module "ecs_service" {
  source = "app.terraform.io/acme/ecs-service/aws"
  version = "~> 2.4.0"

  vpc_id             = module.vpc.vpc_id
  private_subnet_ids = module.vpc.private_subnet_ids
  container_image    = "acme/api:1.8.2"
  desired_count      = 3

  # Platform defaults enforced inside the module
  tags = local.common_tags
}

# Inside ecs-service module, nested child for repeated log groups
module "log_groups" {
  for_each = toset(["app", "sidecar", "init"])
  source   = "./modules/log-group"

  name              = "${var.service_name}-${each.key}"
  retention_in_days = var.log_retention_days
}

Versioning Discipline: Semantic Versioning, Constraints and Breaking Changes

Versioning is where informal infrastructure code becomes a reliable dependency. Without pinned versions, a minor change to a shared module can ripple into failed plans across a dozen teams. I enforce semantic versioning (SemVer) for every shared module: MAJOR.MINOR.PATCH, where patch is for bug fixes, minor for backward-compatible features, and major for breaking changes.

The registry and Terraform language both support version constraints, and how you use them matters. Root configurations should pin to ~> or = constraints to avoid surprise upgrades. Modules themselves should not pin their own dependencies to exact versions; instead, specify minimum compatible versions with >= in required_providers and let the root decide. In my experience, modules that pin exact provider versions cause dependency hell for callers.

Communicating Breaking Changes Clearly

A breaking change is any change that requires callers to modify their code to keep a working plan. Renaming a variable, changing a variable type from string to object, removing an output, or altering default behavior that affects resource replacement all qualify. I've found that the only scalable way to handle this is a changelog and migration guide in the repository, plus deprecation warnings across one minor release before removal.

For example, if you need to rename instance_type to instance_types to support mixed instances, keep the old variable for one minor version, add a validation that emits a clear error message directing users to the new variable, and remove it in the next major. Avoid silent behavior changes; if a default change will cause resource recreation, call it out explicitly and bump the major version.

Constraint Strategies for Different Consumers

Platform teams and product teams need different strategies. Platform root modules that provision landing zones can often use version = "~> 1.2" to receive patches automatically while holding off on minors until tested. Product team stacks that deploy customer-facing services should use version = "= 1.2.4" and upgrade intentionally via pull request. Both approaches rely on automated testing of the upgrade path with terraform plan in CI.

# versions.tf - declaring compatibility, not pinning exactness
terraform {
  required_version = ">= 1.5.0"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 5.0, < 6.0"
    }
  }
}

# Root caller - precise constraint at the edge
module "network" {
  source  = "app.terraform.io/acme/network/aws"
  version = "~> 3.1.0" # allows 3.1.x patches, not 3.2.0

  name       = "prod-vpc"
  cidr_block = "10.10.0.0/16"
}

Publishing to the Registry: Private vs Public Workflows and Automation

The Terraform Registry, whether public at registry.terraform.io or private in Terraform Cloud / HCP Terraform, turns a Git repository into a distributable versioned module. The mechanics are straightforward: a repository named terraform-- with tagged releases and a valid structure is automatically indexed. The discipline around it is what separates ad-hoc sharing from a dependable supply chain.

For private registries, I recommend a single GitHub organization per registry namespace. Each module gets its own repository with branch protection on main, required status checks, and tag-based releases. Public modules demand stricter documentation and example coverage because you cannot control how they are consumed; private modules benefit from tighter integration with your SSO, Sentinel policies, and run tasks.

Source Type Versioning Discovery & Docs Best For
Local Path (./modules/vpc) None; always current Manual, repo README only Monorepo, tightly coupled stacks
Git URL (git::https://...) Ref, branch, or tag; mutable branches risky Git history, no registry UI Temporary sharing, cross-repo without registry
Public Registry (registry.terraform.io) SemVer, immutable versions, constraints Auto-generated docs, search, verification badge Open source, community reuse
Private Registry (app.terraform.io) SemVer, team-scoped, access controlled Private search, SSO, Sentinel integration Organizational standards, regulated environments

Automation is non-negotiable. I configure a GitHub Actions workflow that on tag push runs terraform fmt -check, terraform validate, tflint, checkov, and generates docs with terraform-docs. If those pass, the tag is published. HCP Terraform picks up the tag and publishes the version automatically; no manual upload. This ensures every published version is tested and documented identically. For teams practicing GitOps, the same tagging discipline pairs well with the promotion models in GitOps with ArgoCD and Flux: Declarative Kubernetes Deployment.

Publishing also means thinking about the consumer's upgrade path. Each release should include a changelog entry describing added, changed, and fixed behavior. I follow Conventional Commits to auto-generate changelogs and use Release Please or similar to propose releases. Avoid publishing from a feature branch; only tags on main should create registry versions. That keeps the registry history linear and auditable.

Hardening Modules for Reuse: Validation, Defaults and Error Handling

A reusable module must fail fast with helpful errors. That starts with validation blocks on variables and precondition and postcondition blocks on resources and outputs (introduced in Terraform 1.2). In my experience, good validations cut support requests in half because users learn the correct input shape before they ever run apply.

Consider an RDS module. Valid inputs for engine_version, instance_class, and allocated_storage are interdependent; certain storage types require specific version constraints. A precondition that checks var.allocated_storage >= 100 when var.storage_type == "io1" prevents an API error that would otherwise surface minutes into an apply. Postconditions can verify that an output meets expectations, such as asserting that a VPC output contains at least two subnets.

Defaults That Reflect Production Safety

Defaults encode your organization's risk tolerance. I default to encrypted storage, deletion protection, and least-privilege IAM, and require callers to explicitly disable them with a variable like allow_force_destroy. This pattern makes risky configurations visible in code review. When a pull request sets deletion_protection = false, reviewers immediately ask why.

Be careful with defaults that cause resource replacement. Changing a default for instance_type or engine_version in a patch release would trigger unexpected recreation. Treat default values as part of the public contract; document them, test drift when they change, and only modify them in minor or major releases with release notes.

Graceful Handling of Optional Resources

Modules often need to conditionally create resources. The modern approach is count with 0/1 or for_each over a filtered collection, combined with dynamic blocks for nested arguments. I prefer for_each on a map where possible because it preserves resource addresses when items are added or removed. When a resource is conditional, make sure outputs handle the null case cleanly using try() or conditional expressions, so callers do not get indexing errors when the resource is disabled.

Error messages should guide remediation. Instead of a generic regex validation failure, include an example of a valid value. Instead of letting the AWS provider return InvalidParameterCombination, add a precondition that explains the combination rule. These small details compound into a module that teams actually enjoy consuming.

Testing and Documentation Strategies That Keep Modules Maintainable

Modules without tests decay. I treat module testing at three levels: static analysis, contract testing, and integration testing. Static analysis runs fast and catches style and security issues: terraform fmt, tflint, and checkov or tfsec. Contract testing validates that variables, outputs, and validations behave as expected using terraform test (the native framework since Terraform 1.6) or Terratest. Integration testing deploys the example configuration to a sandbox account and verifies outputs.

Native terraform test has changed how I test modules. You can write .tftest.hcl files that run plan or apply in isolated temporary states, assert on outputs, and test preconditions without needing Go. For more complex scenarios that require inspecting real cloud resources or handling eventual consistency, Terratest remains valuable. The key is to run both in CI on every pull request and to keep fixtures small so tests finish in minutes, not hours. For a deeper setup, see Infrastructure Testing: Terratest, Checkov and Policy-as-Code Validation.

Documentation is the other half of maintainability. I generate input/output tables, requirements, and resource lists with terraform-docs markdown table and enforce that the README is up to date via a CI check that fails if docs are stale. Each module gets a examples/basic and examples/complete directory with a README explaining what the example demonstrates. I've found that examples are the de facto documentation most engineers read first; keep them runnable and tested.

Finally, consider deprecation and discoverability. When a module is superseded, mark it as deprecated in the registry, archive the repository, and point to its successor. HCP Terraform's private registry supports deprecation warnings that surface during plan, which gives consumers time to migrate. A quarterly review of registry usage analytics helps identify unused or duplicated modules that can be consolidated, reducing the maintenance surface area for the platform team.

Frequently Asked Questions

Should I use a single monorepo for all modules or one repository per module?

One repository per publishable module. The registry model maps one repository to one module, and versioning, tagging, and access control are cleaner that way. A monorepo works for local-path modules inside a single stack, but it complicates registry publishing, changelog generation, and independent versioning. I keep shared CI workflows in a central template repository and reuse them across module repos to avoid duplication.

How do I avoid breaking existing callers when I need to change a variable type?

Introduce the new variable alongside the old one and mark the old as deprecated with a validation message. Support both for one minor release, preferring the new when both are set, and add a lifecycle or migration note. In the next major version, remove the old variable. Use moved blocks where resource addresses change to preserve state, and include a detailed upgrade guide with find-and-replace examples.

When should I publish to the public registry versus keeping a module private?

Publish publicly when the module solves a general problem without organization-specific policy and you are willing to maintain SemVer, respond to issues, and keep documentation current. Keep modules private when they encode internal standards, reference private AMIs or endpoints, or integrate with internal systems. Many teams do both: contribute generic modules publicly and maintain thin private wrappers that layer company policy on top.

How do I test modules that provision expensive or slow resources?

Keep integration tests focused and use mocked or ephemeral resources where possible. For native tests, use terraform test with plan assertions to validate logic without creating infrastructure. For real applies, deploy a minimal example to a sandbox account nightly rather than on every PR, and use Terratest with short lifecycle tests that destroy immediately after. Combine this with policy checks like Checkov to catch misconfigurations statically before any cloud spend.

Related Articles

References & Standards: Kubernetes Documentation · Docker Documentation · Terraform Documentation