OpsCanary
Back to daily brief
terraformmodulesPractitioner

Mastering Terraform Modules: Building Reusable Infrastructure

5 min read HashiCorp DocsApr 23, 2026
PractitionerHands-on experience recommended

Terraform modules exist to simplify the management of infrastructure by grouping related resources together. This modular approach allows you to reuse code across different configurations, reducing duplication and enhancing maintainability. When you create a module, you define a new directory and place your .tf files inside, just like you would for the root module. Terraform can load these modules from local paths or remote repositories, making it easy to share and version your infrastructure code.

To create a module, you need to define input variables to accept values from the calling module and output values to return results back. This two-way communication is crucial for building flexible and reusable modules. Avoid creating modules that are merely thin wrappers around single resource types; they should encapsulate multiple resources that work together. This approach not only promotes cleaner code but also supports module composition, allowing you to build complex infrastructures without deep nesting.

In production, remember that modules can significantly reduce complexity, but they also require careful design. Ensure you document any refactoring blocks to track changes in resource names and module structure over time. This practice can save you from headaches during updates and debugging. Always consider the scale of your infrastructure when deciding how to structure your modules, as overly simplistic modules can lead to maintenance challenges down the line.

Key takeaways

  • Create a new directory for each module and include multiple .tf files.
  • Define input variables to accept values from the calling module.
  • Use output values to return results for further use in configurations.
  • Avoid thin wrappers around single resource types; aim for encapsulating multiple resources.
  • Document refactoring blocks to track changes in your module structure.

Why it matters

In a production environment, using modules can drastically reduce code duplication and improve maintainability, leading to faster deployment cycles and fewer errors.

Code examples

mdx-inline-code
terraform plan
mdx-inline-code
terraform apply
mdx-inline-code
aws_instance

When NOT to use this

Do not recommend writing modules that are just thin wrappers around single other resource types. The official docs don't call out specific anti-patterns here. Use your judgment based on your scale and requirements.

Want the complete reference?

Read official docs

Test what you just learned

Quiz questions written from this article

Take the quiz →

Get the daily digest

One email. 5 articles. Every morning.

No spam. Unsubscribe anytime.