Terraform Modules
As your infrastructure grows, a single Terraform configuration file becomes hard to manage. Modules allow you to group resources together and reuse them across projects. A module is a container for multiple resources that are used together.
What Is a Module?
A module is a collection of
.tf files in a directory. You can call a module from your root configuration to include its resources. Modules can be local (filesystem) or remote (Terraform Registry, GitHub, S3).Modules are the primary way to package and reuse Terraform configurations.
Creating a Simple Module
Create a directory
modules/aws-instance with a file main.tf:variable "ami" { type = string }
variable "instance_type" { default = "t2.micro" }
resource "aws_instance" "this" {
ami = var.ami
instance_type = var.instance_type
}
output "id" {
value = aws_instance.this.id
}Using the Module in Root
In your root
main.tf:module "web" {
source = "./modules/aws-instance"
ami = "ami-0c55b159cbfafe1f0"
}
output "web_id" {
value = module.web.id
}Run terraform init to install local modules.Using Modules from Terraform Registry
The public Terraform Registry hosts thousands of modules. Example: AWS VPC module.
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "5.0.0"
name = "my-vpc"
cidr = "10.0.0.0/16"
}Module Outputs
Modules can expose outputs, which you can access with
module.<name>.<output>.Module Versioning
For remote modules, specify a version to avoid breaking changes. Use version constraints like
>= 1.0.0.Two Minute Drill
- Modules are reusable collections of Terraform resources.
- Define module in its own directory with variables and outputs.
- Call module with
module "name" { source = "..." }. - Use Terraform Registry for community modules.
- Always version remote modules.
Need more clarification?
Drop us an email at career@quipoinfotech.com
