Skip to main content
Building a well-structured, versioned Terraform module ensures consistency, reusability, and easy collaboration across teams. In this guide, we’ll walk through:
  • Directory layout
  • Input declarations and validations
  • Resource definitions
  • Output exports
  • Example usage
  • Versioning best practices
  • Documentation tips

1. Module Directory Structure

Begin by creating a top-level folder for your module. Inside, organize files as follows:

2. Declare and Parameterize Inputs

In variables.tf, declare all module inputs, set types, defaults, and add validation:
Use validation blocks to enforce constraints early and prevent invalid configurations.

3. Define Resources Using Inputs

Start by pinning provider versions:
Then, reference your variables in main.tf:
Avoid hard-coding AMI IDs across regions. Consider using data "aws_ami" to dynamically look up the latest image.

4. Expose Outputs

In outputs.tf, export the values that other modules or root configurations will consume:
If outputs contain sensitive data (e.g., private keys), set sensitive = true to prevent accidental exposure.

5. Provide Usage Examples

Under examples/simple/main.tf, demonstrate a minimal working invocation:
Run the following commands:

6. Versioning and Collaboration

Follow these guidelines to keep your module maintainable:
  • Use Semantic Versioning (e.g., v1.0.0, v1.1.0)
  • Tag releases in Git (git tag v1.0.0)
  • Maintain a CHANGELOG.md to record feature additions and fixes

7. Documentation and Comments

Consistently document your module to help users onboard quickly:
  • Add a header comment in each .tf file summarizing its purpose
  • Comment complex logic (e.g., loops, conditionals) in main.tf
  • Describe variable constraints and recommended values next to their declarations

Watch Video