TerraformIntermediate

Terraform Modules: Building Reusable Infrastructure Components

Admin KC
9 min read

TL;DR

Master Terraform modules to create reusable, maintainable infrastructure components. Learn about module creation, versioning, and best practices for infrastructure as code.

Terraform Modules: Building Reusable Infrastructure Components

Executive Summary

Reusable infrastructure components are an interface design problem before they are a coding problem. A Terraform module succeeds when a consumer can use it correctly from its README alone: clear inputs with validation, predictable outputs, declared version constraints, and behaviour that does not change silently between releases. This guide covers building modules as components — structure, input validation, version constraints, provider passing, registry publishing with semantic versioning, and testing with examples and automated tests. After reading it, you should be able to design a module other teams can adopt safely, and to evaluate third-party modules before depending on them.

Why This Matters

A module is a promise. Every team that adopts yours builds on the assumption that its interface is stable and its defaults are sane. Break that promise — rename a variable, change a default, tighten a resource's behaviour in a patch release — and the failure surfaces in someone else's production plan, under their change freeze, as your bug. The opposite failure is just as real: a module so configurable that using it requires understanding its internals is not a component at all, just relocated complexity. Getting the interface right is what separates infrastructure libraries that standardise an organisation from shared code that teams quietly fork and abandon.

Core Concepts

Structure and the Standard Layout

A component-grade module separates interface from implementation and declares its own requirements:

module-name/
├── main.tf       # Main module configuration
├── variables.tf  # Input variables
├── outputs.tf    # Output values
├── versions.tf   # Version constraints
└── README.md     # Documentation

The versions.tf file is not decoration. It states the oldest Terraform and provider versions the module is tested against, so consumers learn about incompatibility at init time rather than mid-apply:

# versions.tf
terraform {
  required_version = ">= 1.0.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

Inputs: Typed, Described, Validated

Variables are the module's public API. Each one gets a type, a description, and a default only where a genuine standard exists. Where the set of legal values is closed, enforce it at the boundary so misuse fails at plan time with a readable message instead of as a provider error three resources deep:

# variables.tf
variable "environment" {
  description = "Environment name"
  type        = string

  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "Environment must be one of: dev, staging, prod."
  }
}

Prefer a small number of meaningful inputs over a pass-through variable for every argument of every resource. If a consumer needs an argument you did not expose, that is a design conversation — sometimes the answer is a new input, and sometimes it is that the consumer's case belongs in a different module.

A Worked Component

The same discipline applied to a small VPC component:

# modules/vpc/main.tf
resource "aws_vpc" "main" {
  cidr_block = var.vpc_cidr

  tags = {
    Name        = var.vpc_name
    Environment = var.environment
  }
}

resource "aws_subnet" "public" {
  count = length(var.public_subnets)

  vpc_id     = aws_vpc.main.id
  cidr_block = var.public_subnets[count.index]

  tags = {
    Name = "${var.vpc_name}-public-${count.index + 1}"
  }
}

# modules/vpc/variables.tf
variable "vpc_cidr" {
  description = "CIDR block for VPC"
  type        = string
}

variable "vpc_name" {
  description = "Name tag for VPC"
  type        = string
}

variable "environment" {
  description = "Environment tag"
  type        = string
}

variable "public_subnets" {
  description = "List of public subnet CIDR blocks"
  type        = list(string)
}

# modules/vpc/outputs.tf
output "vpc_id" {
  description = "ID of the created VPC"
  value       = aws_vpc.main.id
}

output "public_subnet_ids" {
  description = "List of public subnet IDs"
  value       = aws_subnet.public[*].id
}

Consumers then treat the component as a black box with a known contract, locally or from a registry:

module "vpc" {
  source = "./modules/vpc"

  vpc_cidr       = "10.0.0.0/16"
  vpc_name       = "my-vpc"
  environment    = "production"
  public_subnets = ["10.0.1.0/24", "10.0.2.0/24"]
}

module "s3_bucket" {
  source  = "terraform-aws-modules/s3-bucket/aws"
  version = "3.15.1"

  bucket = "my-unique-bucket"
  acl    = "private"

  versioning = {
    enabled = true
  }
}

Providers: Declare Requirements, Let the Caller Configure

A reusable module declares which providers it needs in required_providers and never contains its own provider blocks. Configuration — region, credentials, aliases — belongs to the root module, which passes configured providers into the call when a non-default one is needed:

module "vpc_west" {
  source = "./modules/vpc"

  providers = {
    aws = aws.us_west_2
  }

  # ... inputs
}

Modules that configure their own providers cannot be composed into multi-region or multi-account designs and silently ignore the caller's credential setup. This is the single most common design flaw in hand-rolled modules, and the hardest to retrofit.

Composition and Internal Flexibility

Components compose by wiring outputs to inputs in the caller, keeping each module ignorant of its siblings:

# modules/web-app/main.tf
module "vpc" {
  source = "../vpc"

  vpc_cidr       = var.vpc_cidr
  vpc_name       = var.vpc_name
  environment    = var.environment
  public_subnets = var.public_subnets
}

module "ec2_instance" {
  source = "../ec2-instance"

  subnet_id     = module.vpc.public_subnet_ids[0]
  instance_type = var.instance_type
  environment   = var.environment
}

Inside a module, dynamic blocks and conditional creation provide controlled flexibility — a security group whose rules come from the caller, a database that can be switched off in ephemeral environments:

# modules/security-group/main.tf
resource "aws_security_group" "this" {
  name        = var.name
  description = var.description
  vpc_id      = var.vpc_id

  dynamic "ingress" {
    for_each = var.ingress_rules
    content {
      from_port   = ingress.value.from_port
      to_port     = ingress.value.to_port
      protocol    = ingress.value.protocol
      cidr_blocks = ingress.value.cidr_blocks
    }
  }
}

# modules/rds/main.tf
resource "aws_db_instance" "this" {
  count = var.create_database ? 1 : 0

  identifier        = var.identifier
  engine            = var.engine
  instance_class    = var.instance_class
  allocated_storage = var.allocated_storage

  # ... other configuration ...
}

Use both sparingly: each one multiplies the behaviour a consumer must predict, and conditional resources complicate outputs, which must be written to tolerate the resource not existing.

Versioning and Registries

Published modules are versioned with semantic version tags in Git, and registries — the public Terraform Registry, or a private registry such as the one in HCP Terraform — serve those tagged releases. Consumers pin versions and upgrade deliberately:

module "vpc" {
  source  = "app.terraform.io/example-corp/vpc/aws"
  version = "~> 2.0.0"  # Allows 2.0.x but not 2.1.0

  vpc_cidr = "10.0.0.0/16"
}

The contract that makes this work: patch releases fix bugs without changing behaviour, minor releases add backward-compatible inputs or resources, and anything that renames an input, removes an output, or changes a default in a way that alters plans is a major release with migration notes. Publish a changelog; consumers should not have to diff your source to decide whether to upgrade.

Testing Components

Two layers are proportionate for shared modules. First, an example configuration that doubles as a smoke test — CI runs init, validate, and plan against it on every change:

# examples/complete/main.tf
module "vpc" {
  source = "../../"

  vpc_cidr       = "10.0.0.0/16"
  vpc_name       = "example-vpc"
  environment    = "dev"
  public_subnets = ["10.0.1.0/24", "10.0.2.0/24"]
}

output "vpc_id" {
  value = module.vpc.vpc_id
}

Second, for modules whose behaviour justifies it, an automated test that applies the example in a sandbox account and asserts on the outputs — Terratest is the established option, and Terraform's native test framework covers many of the same cases without a second toolchain:

// test/vpc_test.go
package test

import (
  "testing"
  "github.com/gruntwork-io/terratest/modules/terraform"
  "github.com/stretchr/testify/assert"
)

func TestVPCModule(t *testing.T) {
  terraformOptions := &terraform.Options{
    TerraformDir: "../examples/complete",
  }

  defer terraform.Destroy(t, terraformOptions)
  terraform.InitAndApply(t, terraformOptions)

  vpcID := terraform.Output(t, terraformOptions, "vpc_id")
  assert.NotEmpty(t, vpcID)
}

Decision Framework

SituationRecommendation
Building a module for your own team onlyLocal source in a shared repository; add registry publishing when a second team adopts it
Adopting a public registry modulePin an exact version; read its defaults and recent changelog before the first apply
Consumer needs an unexposed argumentAdd a validated input with a behaviour-preserving default, or decline and document why
Module needs a non-default provider configurationAccept providers through the call's providers argument; never configure providers inside the module
Releasing a change that alters existing plansMajor version bump with migration notes in the changelog
Module interface keeps growing flagsSplit into two components with narrower jobs

Implementation Checklist

  • [ ] Standard layout present, including versions.tf with tested Terraform and provider constraints
  • [ ] No provider blocks inside the module; provider requirements declared, configuration left to callers
  • [ ] Every input is typed and described; closed value sets are enforced with validation blocks
  • [ ] Outputs cover everything a consumer legitimately needs, with descriptions
  • [ ] README documents usage, inputs, and outputs, generated from code where possible
  • [ ] At least one example under examples/ runs in CI (init, validate, plan at minimum)
  • [ ] Releases carry semantic version tags and a changelog; breaking changes are major releases
  • [ ] Consumers pin exact versions, and upgrades are reviewed through plan output
  • Trade-offs

    Every input you add is a commitment to support it; every input you omit is a consumer who may fork. Component design is the ongoing management of that tension, and it never fully resolves. Version discipline also has a cost: consumers on old majors accumulate, and maintaining several release lines is real work. Testing shared modules properly means sandbox accounts and apply-level tests, slower and more expensive than the unit-test habits teams bring from application code. And a successful module creates organisational coupling — its maintainers become a platform team whether or not anyone planned that.

    When Not to Use

  • One-off infrastructure: write resources directly. A component earns its interface only on the second consumer.
  • A thin wrapper over a single resource: if the module adds no defaults, validation, or composition, it adds only indirection.
  • Copying a large public module into your repo to tweak it: consume it pinned, and raise missing features upstream or compose around it; a fork inherits all maintenance.
  • Forcing every team onto one module for a genuinely divergent need: two honest components beat one component with a mode flag for every difference.
  • Application configuration and in-instance setup: modules organise infrastructure resources; what runs inside them belongs to configuration management or image builds.
  • Conclusion

    A reusable module is a maintained product with a contract: validated inputs, honest outputs, declared constraints, and versions that mean something. Design the interface before the internals, let callers own provider configuration, and test through examples that CI actually runs. Modules built to that standard become the way an organisation's infrastructure decisions compound instead of fragmenting.

    References

  • Terraform Module Documentation
  • Terraform Registry
  • Module Development Guide
  • Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.