Modules Creation
Terraform modules are reusable units of infrastructure code that promote consistency, reduce duplication, and simplify complex configurations. By encapsulating resources, variables, and outputs into modular components, teams can streamline deployment workflows and maintain scalable infrastructure. This section guides you through creating, structuring, and reusing Terraform modules effectively.
Creating Terraform Modules¶
A module is a directory containing Terraform configuration files that define resources, variables, and outputs. To create a module, follow these steps:
1. Define Input Variables¶
Input variables allow users to customize a module’s behavior. Define them in a variables.tf file:
# variables.tf
variable "bucket_name" {
description = "Name of the S3 bucket"
type = string
default = "example-bucket"
}
variable "region" {
description = "AWS region for bucket creation"
type = string
default = "us-west-1"
}
2. Configure Resources¶
Create resources in a main.tf file, using variables for dynamic configuration:
3. Define Output Values¶
Expose useful values from the module via outputs.tf:
# outputs.tf
output "bucket_arn" {
description = "ARN of the created S3 bucket"
value = aws_s3_bucket.example.arn
}
4. Structure the Module Directory¶
Organize your module into a directory, e.g., modules/s3-bucket, containing:
Reusing Terraform Modules¶
To reuse a module, call it in a parent configuration using the module block. For example:
1. Call the Module in main.tf¶
# main.tf
module "s3_bucket" {
source = "./modules/s3-bucket"
bucket_name = "production-bucket"
region = "us-east-1"
}
2. Access Module Outputs¶
Reference outputs from the module in the parent configuration:
3. Pass Variables via CLI¶
Use the CLI to override default variables:
Best Practices for Reusability¶
-
Use Semantic Versioning
Tag modules with version numbers (e.g.,v1.0.0) to ensure compatibility across environments. -
Document Variables and Outputs
Include clear descriptions invariables.tfandoutputs.tfto guide users. -
Test in Isolation
Validate modules independently usingterraform validateandterraform planbefore integrating them into larger configurations. -
Avoid Hardcoding Sensitive Data
Use environment variables or secure secret management tools instead of embedding credentials in modules. -
Leverage Remote Modules
For shared modules, publish them to a registry (e.g., Terraform Registry) and reference them viasource = "hashicorp/aws".
Key takeaways¶
- Modularize infrastructure to reduce duplication and improve maintainability.
- Use variables for flexible configuration and outputs to share values between modules.
- Version modules to ensure stability and compatibility across deployments.
- Document thoroughly to enable seamless reuse by other teams or projects.
- Test and validate modules in isolation before integrating them into production workflows.