How to Use Modules for Reusability in Terraform
In Terraform, you use
modules to package and reuse infrastructure code by creating a folder with resources and calling it from your main configuration using the module block. This helps keep your code organized, reduces repetition, and makes managing infrastructure easier.Syntax
A Terraform module is a folder with Terraform files defining resources. You use the module block in your main configuration to call this folder. The key parts are:
- source: path or URL to the module folder
- inputs: variables passed to the module
- outputs: values the module returns
terraform
module "example_module" { source = "./modules/example" variable_name = "value" } output "example_output" { value = module.example_module.output_name }
Example
This example shows a simple module that creates an AWS S3 bucket and how to use it in the main Terraform file.
terraform
# modules/s3_bucket/main.tf resource "aws_s3_bucket" "bucket" { bucket = var.bucket_name acl = "private" } output "bucket_id" { value = aws_s3_bucket.bucket.id } # modules/s3_bucket/variables.tf variable "bucket_name" { type = string } # main.tf provider "aws" { region = "us-east-1" } module "my_bucket" { source = "./modules/s3_bucket" bucket_name = "my-unique-bucket-12345" } output "bucket_id" { value = module.my_bucket.bucket_id }
Output
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Outputs:
bucket_id = my-unique-bucket-12345
Common Pitfalls
Common mistakes when using modules include:
- Not using
sourcecorrectly, causing Terraform to fail finding the module. - Forgetting to define or pass required variables to the module.
- Trying to output values not declared in the module's
outputblocks. - Hardcoding values inside modules instead of using variables, reducing reusability.
terraform
# Wrong: Missing source module "bad_module" { bucket_name = "name" } # Right: Correct source and variables module "good_module" { source = "./modules/s3_bucket" bucket_name = "name" }
Quick Reference
| Concept | Description |
|---|---|
| module | A container for multiple resources used together |
| source | Path or URL to the module folder |
| variables | Inputs to customize module behavior |
| outputs | Values returned from the module |
| module block | How to call a module in your Terraform config |
Key Takeaways
Use modules to package reusable Terraform code and avoid repetition.
Always specify the module source and pass required variables.
Define outputs in modules to expose useful information.
Keep modules generic by using variables instead of hardcoded values.
Test modules independently before using them in main configurations.