What are Terraform modules best practices?
Answer
Terraform module best practices: Single purpose: each module should do one thing well (a VPC module, a GKE cluster module). Avoid "do everything" mega-modules. Interface design: expose the minimum necessary inputs and outputs. Hide internal complexity. Version pinning: always use version constraints on module sources. Documentation: document all inputs and outputs with descriptions. Use terraform-docs to auto-generate README. Examples: include a working example in an examples/ directory. Testing: use Terratest (Go) or Terraform's built-in testing framework (.tftest.hcl) to validate modules. Semantic versioning: version modules with semver; breaking changes bump major version. No provider configuration in modules: modules should not configure providers — pass them from the root. Avoid hardcoding: make regions, tags, and names configurable. Use the official AWS/Azure/GCP Registry modules as reference implementations.
More Terraform / IaC Questions
View all →- Intermediate What is the Terraform state locking mechanism?
- Intermediate How do you handle sensitive values in Terraform?
- Intermediate What are Terraform Provisioners and when should you avoid them?
- Intermediate What is Terraform import?
- Intermediate How do you structure Terraform code for large teams?