πΉ What Is a Terraform Module?
A Terraform module is a self-contained set of Terraform files that define a reusable infrastructure component.
In simple terms:
A module is Terraform code that can be called multiple times with different inputs.
Terraform already uses modules implicitly:
The root directory is a module
Child modules are reusable blocks
1οΈβ£ Creating a Simple EC2 Module
modules/ec2/main.tf
resource "aws_instance" "this" {
ami = var.ami
instance_type = var.instance_type
subnet_id = var.subnet_id
tags = var.tags
}
modules/ec2/variables.tf
variable "ami" {
type = string
}
variable "instance_type" {
type = string
}
variable "subnet_id" {
type = string
}
variable "tags" {
type = map(string)
}
modules/ec2/outputs.tf
output "instance_id" {
value = aws_instance.this.id
}
2οΈβ£ Calling a Module from Root Configuration
In your root Terraform directory:
module "web_ec2" {
source = "./modules/ec2"
ami = data.aws_ami.amazon_linux.id
instance_type = "t2.micro"
subnet_id = data.aws_subnet.public.id
tags = {
Name = "web-server"
Env = "dev"
}
}
Terraform treats this module like a function call:
Inputs β variables
Outputs β return values
3οΈβ£ Using Module Outputs
You can reference module outputs easily:
output "web_instance_id" {
value = module.web_ec2.instance_id
}
This enables:
Cross-module communication
Cleaner root configurations
Better composition of infrastructure
4οΈβ£ Modules Across Environments
One of the biggest benefits of modules is environment reuse.
The same module can be used for:
Dev
QA
Prod
Only inputs change.
module "ec2_dev" {
source = "./modules/ec2"
instance_type = "t2.micro"
}
module "ec2_prod" {
source = "./modules/ec2"
instance_type = "t3.large"
}
β Same code
β Different behavior
5οΈβ£ Why Modules Are Mandatory in Real Projects
In professional Terraform setups:
β Copyβpaste is forbidden
β
Modules enforce DRY (Donβt Repeat Yourself)
β
Changes happen in one place
β
Code reviews are easier
β
Bugs reduce drastically
Modules also enable:
Versioning
Team collaboration
CI/CD pipelines
Terraform Registry usage
Top comments (0)