Terraform Modules and Reusability
What you'll learn: How to organize Terraform code into reusable modules that standardize infrastructure patterns across different environments and projects.
Why Modules Matter
As your infrastructure grows, you'll find yourself copying and pasting Terraform configurations between projects or environments. Modules solve this problem by letting you package infrastructure patterns into reusable components. Think of modules like functions in programming—you write the logic once, then call it with different parameters wherever needed.
How Modules Work
A Terraform module is simply a collection of .tf files in a directory. You've already been using a module—your root configuration is itself a module! When you create custom modules, you encapsulate related resources and expose configurable inputs (variables) and outputs.
For example, instead of duplicating VPC setup code across staging and production, you create a vpc module once. Each environment then calls that module with different parameters (CIDR blocks, region, naming conventions).
The Anatomy of a Module
Modules typically contain:
- Resources: The infrastructure components being created
- Input variables: Parameters that customize the module's behavior
- Outputs: Values the module exposes to its caller
- Documentation: Describing what the module does and how to use it
When you reference a module in your configuration, Terraform fetches it, passes your variables, provisions the resources, and returns any outputs. This abstraction lets teams maintain consistent infrastructure patterns while adapting to specific needs.
Benefits of Modular Design
Modules reduce duplication, enforce standards, and simplify maintenance. Update a bug fix or security improvement in one module, and all environments using it benefit. They also enable separation of concerns—platform teams can maintain shared modules while application teams consume them.
Key Takeaway: Terraform modules transform infrastructure code from copy-paste configurations into reusable, testable, maintainable components that scale across your organization.