Chapter Six

Modules

The unit of reuse in Terraform — how a directory of configuration becomes a versioned, black-box component with a typed interface, sourced and pinned the way you pin a library.

7 topics

A module is just a directory of .tf files you call with inputs — and that small idea is how you stop copy-pasting a VPC definition across ten projects and start versioning one. Every configuration is already a module: the directory you run Terraform in is the root module, and the moment it calls another directory with a module block, you are composing.

This chapter is about that composition. What a module is and what its interface consists of, how inputs and outputs form a contract, how you source and pin a module so the build is reproducible, the public Registry and its widely-used AWS modules, version constraints and the ~> operator, how to compose modules without nesting them into a maze, and finally the principles that make a module others adopt happily instead of forking in frustration.

Topics in This Chapter

Topic 35
What a Module Is
Root versus child modules, the input/resources/output interface, why modules beat copy-paste, and the fact that a module is nothing more than a directory of configuration called with values.
ConceptModules
Topic 36
Module Inputs and Outputs
The two channels a module talks through. Inputs as a typed public API, outputs as deliberate return values, encapsulation of everything in between, and what is safe to change without breaking callers.
InterfaceModules
Topic 37
Calling and Sourcing Modules
The module block and its source argument — local paths, Registry references, git, and archives — how init downloads them, and why a branch ref breaks reproducibility.
ModulesSourcing
Topic 38
The Public Module Registry
The terraform-aws-modules collection and how to evaluate, pin, and wrap a Registry module — the weeks it saves against the large opinionated dependency it pulls in.
RegistryModules
Topic 39
Versioning and Version Constraints
Constraint syntax, the pessimistic operator, and how SemVer plus the lock file give you "new patches automatically, breaking changes never by surprise."
VersioningModules
Topic 40
Composition and Nested Modules
Wiring one module's outputs into another's inputs from a root module, why shallow beats deeply nested, the wrapper pattern, and how module wiring can hide a dependency cycle.
CompositionModules
Topic 41
Designing Reusable Modules
Module as a product with users: a minimal interface, sensible defaults with escape hatches, validation, documentation and examples, and SemVer discipline.
DesignModules