- 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:| Path | Purpose |
|---|---|
| my-module/ | Root directory for your module |
| ├─ main.tf | Core resource definitions |
| ├─ variables.tf | Input variable declarations & validations |
| ├─ outputs.tf | Exported values for external configurations |
| └─ examples/simple/main.tf | Minimal example demonstrating module usage |
2. Declare and Parameterize Inputs
Invariables.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:main.tf:
Avoid hard-coding AMI IDs across regions. Consider using
data "aws_ami" to dynamically look up the latest image.4. Expose Outputs
Inoutputs.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
Underexamples/simple/main.tf, demonstrate a minimal working invocation:
| Command | Description |
|---|---|
| terraform init | Initialize plugins and backend |
| terraform plan | Preview planned changes |
| terraform apply | Apply the configuration |
| terraform destroy | Tear down the created resources |
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.mdto record feature additions and fixes
7. Documentation and Comments
Consistently document your module to help users onboard quickly:- Add a header comment in each
.tffile summarizing its purpose - Comment complex logic (e.g., loops, conditionals) in
main.tf - Describe variable constraints and recommended values next to their declarations