Build a Reusable Terraform AWS Module with Best Practices
Create a production-ready, reusable Terraform module for AWS services with proper structure, validation, security, and documentation.
๐ The Prompt
Create a reusable Terraform module for provisioning [AWS_SERVICE (e.g., ECS Fargate cluster, RDS PostgreSQL, S3 + CloudFront static site, VPC with subnets)] on AWS following HashiCorp's module best practices.
Module Requirements:
- AWS Region: [AWS_REGION (e.g., us-east-1)]
- Terraform Version: >= [TF_VERSION (e.g., 1.5)]
- AWS Provider Version: >= [PROVIDER_VERSION (e.g., 5.0)]
- Purpose: [USE_CASE_DESCRIPTION (e.g., host a containerized API behind an ALB, serve a static website with CDN)]
Generate the following file structure with complete code:
1. **main.tf**: Core resource definitions with:
- Logical resource naming using a [NAMING_CONVENTION (e.g., {project}-{environment}-{resource})] pattern.
- Conditional resource creation using `count` or `for_each` based on feature flags.
- Proper use of `depends_on` only where implicit dependencies are insufficient.
- Data sources for referencing existing resources (e.g., existing VPC, IAM policies).
2. **variables.tf**: Input variables with:
- Type constraints (string, number, list, map, object with nested types).
- Sensible defaults for optional parameters.
- Validation blocks with custom error messages for critical inputs.
- Sensitive flag for secrets.
3. **outputs.tf**: Expose key resource attributes (ARNs, endpoints, IDs) needed by dependent modules.
4. **versions.tf**: Required providers and Terraform version constraints.
5. **locals.tf**: Computed values, merged tags following [TAGGING_STRATEGY (e.g., Environment, Project, ManagedBy, CostCenter)] standards.
6. **README.md**: Auto-doc compatible description with usage example showing how to call this module from a root configuration.
7. **examples/basic/main.tf**: A working example that calls the module with minimal required inputs.
Security Requirements:
- Apply least-privilege IAM policies.
- Enable encryption at rest and in transit where applicable.
- Use security groups with minimal ingress rules.
- Enable logging and monitoring (CloudWatch, access logs).
Include inline comments explaining architectural decisions and trade-offs.
๐ก Tips for Better Results
Be specific in [AWS_SERVICE] โ naming the exact service and topology (e.g., 'multi-AZ RDS PostgreSQL with read replica') yields much more accurate code. Always review generated IAM policies against the principle of least privilege before applying. Run `terraform validate` and `terraform plan` in a sandbox account before targeting production.
๐ฏ Use Cases
Cloud engineers and platform teams use this when building standardized, shareable infrastructure modules that enforce organizational best practices across multiple projects.