Chapter Seven

Modules

Turning the pile of bucket, Pub/Sub, Cloud Run, and BigQuery resources from earlier chapters into one reusable ingest-pipeline module — and reaching for Google's Cloud Foundation Toolkit for the project, network, and storage scaffolding around it.

7 topics

A module is the unit of reuse in Terraform, and it is a smaller idea than it sounds: any directory of .tf files is a module, so you have been writing them since your first configuration. What this chapter adds is the discipline of treating a directory as a black box — inputs in, outputs out, internals private — so the six interdependent resources of the Hatch ingest pipeline become one thing you call once per event type instead of copy-paste you maintain in ten places.

The running example is Layer A, the Hatch pipeline. You will package its bucket, Pub/Sub topic, Cloud Run service, BigQuery dataset, and service account into a single ingest-pipeline module, then consume Google's Cloud Foundation Toolkit modules for the undifferentiated plumbing around it — the project, the VPC, the storage scaffolding. The seven topics move from what a module is, through inputs, sourcing, versioning, and composition, to the design principles that separate a module other teams adopt from one they fork in frustration.

Topics in This Chapter

Topic 41
What a Module Is
Every directory of .tf files is a module. Root versus child, why a child has no backend, and what encapsulation means for reaching into the Hatch ingest pipeline.
ConceptModules
Topic 42
Module Inputs and Outputs
The contract in and the contract out — the entire public surface of the black box. Required versus defaulted inputs, sensitive outputs, and designing the boundary as intent.
Interface
Topic 43
Calling and Sourcing Modules
The module block and its source argument: local paths, the Registry, git, and GCS. Why init downloads remote sources and which source type takes a version.
Sourcing
Topic 44
The Cloud Foundation Toolkit
Google's own production-grade Terraform modules under terraform-google-modules: project-factory, network, GKE, cloud-storage. When to adopt CFT and when to write your own.
CFTRegistry
Topic 45
Versioning and Version Constraints
Pinning a registry module with the pessimistic operator, why an unpinned module breaks reproducibility, reading the CHANGELOG before a major bump, and how git sources pin differently.
Versioning
Topic 46
Composition and Nested Modules
Modules calling modules. Implicit provider inheritance versus explicit passing with configuration_aliases, keeping the tree shallow, and reading a composed plan.
Composition
Topic 47
Designing Reusable Modules
The interface is the expensive part to change. Sensible defaults versus over-parameterizing, examples/ and README as the contract, and why single-purpose beats do-everything.
Design