Terraform by Example: Modules
Modules allow you to encapsulate and reuse infrastructure configurations. This sample code demonstrates how to call a child module with versioning and input variables.
Code
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "5.0.0"
name = "my-vpc"
cidr = "10.0.0.0/16"
azs = ["us-east-1a", "us-east-1b"]
private_subnets = ["10.0.1.0/24", "10.0.2.0/24"]
public_subnets = ["10.0.101.0/24", "10.0.102.0/24"]
enable_nat_gateway = true
tags = {
Terraform = "true"
Environment = "dev"
}
}
# Accessing module outputs
output "vpc_id" {
value = module.vpc.vpc_id
}Explanation
Modules are the primary way to package and reuse resource configurations in Terraform. A module is simply a directory containing Terraform files. The module in the current working directory is the "root module," which can call other "child modules" to encapsulate logic and promote the DRY (Don't Repeat Yourself) principle. Using modules allows you to standardize infrastructure components across your organization.
When calling a module, the source argument is mandatory and tells Terraform where to find the module code (e.g., a local path, a Git repository, or the Terraform Registry). It is highly recommended to specify a version constraint for external modules to ensure stability and prevent unexpected breaking changes from upstream updates.
Modules communicate through inputs and outputs. Arguments inside the module block correspond to the input variables defined in the child module. Conversely, to access values returned by the module, you use the syntax module.name.output_name. This clear interface makes modules composable and easy to test.
Code Breakdown
source points to the official AWS VPC module on the registry.version = "5.0.0" locks the module to a specific release for stability.cidr = "..." passes a value to the module's input variable.enable_nat_gateway = true toggles a feature flag within the module.tags block passes a map of tags to be applied to all resources.module.vpc.vpc_id accesses an output declared inside the VPC module.
