Writing a reusable Terraform module
Building a small VPC module in Terraform with inputs, validation and outputs, calling it from two root modules with different settings, and pinning it to a git tag so a change to the module can't surprise a project that didn't ask for it.
After a few Terraform projects you notice the same blocks showing up everywhere. A VPC, two subnets, an internet gateway, route tables. Copying them between projects works, but now what happens is you fix a bug in one copy and the other three keep it.
In this blog we will write a small VPC module, call it from two different root modules with different settings, and then version it with git tags so each project chooses when to take a new version. Level: intermediate. You should be fine with variables, for_each and outputs (the previous post covers them). I used Terraform 1.17.1 and AWS provider 6.73.0.
What a module is
Every folder of .tf files is a module. The folder you run terraform plan in is the root module. A module block in it pulls in another folder, gives it inputs and gets outputs back. That's basically the whole idea. There's no special syntax for "writing" a module, you just write normal Terraform in a folder and decide what goes in as variables and what comes out as outputs.
The layout for this post:
modules/
vpc/
versions.tf
variables.tf
main.tf
outputs.tf
live/
shorty/
main.tf
sandbox/
main.tf
shorty is the URL shortener that the series builds (the standard library API post is where its code starts). It gets two zones and a NAT gateway. sandbox is a throwaway VPC for trying things, one zone and no NAT.
The inputs
Start from the inputs, because they're the module's contract. Anything not in here, the caller can't change.
variable "name" {
description = "Name used for the VPC and as a prefix for everything in it."
type = string
}
variable "cidr_block" {
description = "CIDR range of the VPC, e.g. 10.20.0.0/16."
type = string
validation {
condition = can(cidrhost(var.cidr_block, 0))
error_message = "cidr_block must be a valid IPv4 CIDR, e.g. 10.20.0.0/16."
}
}
variable "azs" {
description = "Availability zones to spread subnets over. One public and one private subnet per zone."
type = list(string)
validation {
condition = length(var.azs) >= 1 && length(var.azs) <= 4
error_message = "Give between 1 and 4 availability zones."
}
}
variable "subnet_newbits" {
description = "Bits added to the VPC prefix for each subnet. 8 turns a /16 into /24 subnets."
type = number
default = 8
}
variable "enable_nat_gateway" {
description = "Create one NAT gateway so private subnets can reach the internet. Costs money every hour."
type = bool
default = false
}
variable "tags" {
description = "Extra tags for every resource."
type = map(string)
default = {}
}
I keep the list short. It's tempting to add a variable for every argument of every resource, and then the module is just the AWS API with extra steps. Five or six inputs that cover the real differences between projects is plenty. If a caller needs something exotic, they can write their own VPC.
enable_nat_gateway defaults to false because a NAT gateway is billed every hour it exists, plus data. I'd rather the expensive thing be opt-in. The description says that too, so nobody has to read the code to find out.
The resources
locals {
# Public subnets take the first netnums, private ones start at 100,
# so adding a zone later never shifts an existing subnet.
public = {
for i, az in var.azs : az => cidrsubnet(var.cidr_block, var.subnet_newbits, i)
}
private = {
for i, az in var.azs : az => cidrsubnet(var.cidr_block, var.subnet_newbits, 100 + i)
}
}
resource "aws_vpc" "this" {
cidr_block = var.cidr_block
enable_dns_support = true
enable_dns_hostnames = true
tags = merge(var.tags, { Name = var.name })
}
resource "aws_internet_gateway" "this" {
vpc_id = aws_vpc.this.id
tags = merge(var.tags, { Name = var.name })
}
resource "aws_subnet" "public" {
for_each = local.public
vpc_id = aws_vpc.this.id
availability_zone = each.key
cidr_block = each.value
map_public_ip_on_launch = true
tags = merge(var.tags, { Name = "${var.name}-public-${each.key}", Tier = "public" })
}
resource "aws_subnet" "private" {
for_each = local.private
vpc_id = aws_vpc.this.id
availability_zone = each.key
cidr_block = each.value
tags = merge(var.tags, { Name = "${var.name}-private-${each.key}", Tier = "private" })
}
resource "aws_route_table" "public" {
vpc_id = aws_vpc.this.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.this.id
}
tags = merge(var.tags, { Name = "${var.name}-public" })
}
resource "aws_route_table_association" "public" {
for_each = aws_subnet.public
subnet_id = each.value.id
route_table_id = aws_route_table.public.id
}
resource "aws_eip" "nat" {
count = var.enable_nat_gateway ? 1 : 0
domain = "vpc"
tags = merge(var.tags, { Name = "${var.name}-nat" })
}
resource "aws_nat_gateway" "this" {
count = var.enable_nat_gateway ? 1 : 0
allocation_id = aws_eip.nat[0].id
subnet_id = aws_subnet.public[var.azs[0]].id
tags = merge(var.tags, { Name = var.name })
depends_on = [aws_internet_gateway.this]
}
resource "aws_route_table" "private" {
vpc_id = aws_vpc.this.id
dynamic "route" {
for_each = var.enable_nat_gateway ? [1] : []
content {
cidr_block = "0.0.0.0/0"
nat_gateway_id = aws_nat_gateway.this[0].id
}
}
tags = merge(var.tags, { Name = "${var.name}-private" })
}
resource "aws_route_table_association" "private" {
for_each = aws_subnet.private
subnet_id = each.value.id
route_table_id = aws_route_table.private.id
}
A few things in there worth a line each.
The subnets are keyed by zone name, not by index. Same reason as in the last post: if you add a third zone later, the existing subnets keep their addresses in state and nothing gets replaced. cidrsubnet cuts the VPC range into pieces. With a /16 and 8 new bits you get /24 subnets, public ones from netnum 0 and private ones from 100. Both counters only depend on the position of the zone in the list, so don't reorder azs once it's applied. Appending is fine.
The NAT parts use count as an on/off switch. That's the one place I still use count. The private route table uses a dynamic block for the same reason: no NAT, no default route, and the private subnets stay fully private.
depends_on on the NAT gateway is there because AWS wants the internet gateway attached before the NAT can work, and nothing in the NAT's arguments refers to it.
Every resource is named this or public/private. Inside a module there's only one VPC, so long names just add noise. From the outside it shows up as module.vpc.aws_vpc.this, which reads fine.
The outputs
output "vpc_id" {
value = aws_vpc.this.id
}
output "vpc_cidr_block" {
value = aws_vpc.this.cidr_block
}
output "public_subnet_ids" {
description = "Public subnet IDs, in the same order as var.azs."
value = [for az in var.azs : aws_subnet.public[az].id]
}
output "private_subnet_ids" {
description = "Private subnet IDs, in the same order as var.azs."
value = [for az in var.azs : aws_subnet.private[az].id]
}
output "nat_gateway_id" {
description = "ID of the NAT gateway, or null when enable_nat_gateway is false."
value = one(aws_nat_gateway.this[*].id)
}
Outputs are the other half of the contract. Callers can't reach inside the module, module.vpc.aws_subnet.public doesn't work from the root, so anything they need has to be an output. Subnet IDs come back as lists in the same order as azs, because that's what most AWS resources want (a load balancer, an ECS service). one() turns the zero-or-one list from count into either the ID or null.
And versions.tf in the module:
terraform {
required_version = ">= 1.11"
required_providers {
aws = {
source = "hashicorp/aws"
version = ">= 6.0"
}
}
}
A module says the minimum it needs, with >=. The root module is the one that pins with ~>. No provider "aws" block inside the module either, it gets the provider from the caller. When I ran init, Terraform printed both constraints together: Finding hashicorp/aws versions matching ">= 6.0.0, ~> 6.0". That's how it combines them.
Two callers
live/shorty/main.tf:
terraform {
required_version = ">= 1.11"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
}
provider "aws" {
region = "ap-south-1"
}
module "vpc" {
source = "../../modules/vpc"
name = "shorty"
cidr_block = "10.20.0.0/16"
azs = ["ap-south-1a", "ap-south-1b"]
enable_nat_gateway = true
tags = {
Project = "shorty"
}
}
output "vpc_id" {
value = module.vpc.vpc_id
}
output "private_subnet_ids" {
value = module.vpc.private_subnet_ids
}
live/sandbox/main.tf is the same file with a different module block:
module "vpc" {
source = "../../modules/vpc"
name = "sandbox"
cidr_block = "10.99.0.0/16"
azs = ["ap-south-1a"]
tags = {
Project = "sandbox"
}
}
Each root has its own state. That's the point of two roots, breaking the sandbox can't touch shorty. When you add a module or change its source, run terraform init again so Terraform installs it.
I ran both plans against moto, a local AWS mock, with fake credentials, because I wasn't going to pay for a NAT gateway to write a blog post. Shorty planned 14 to add: the VPC, the internet gateway, two public and two private subnets, two route tables, four associations, the Elastic IP and the NAT. Sandbox planned 8 to add. The subnet CIDRs came out like I wanted.
# module.vpc.aws_subnet.private["ap-south-1a"] will be created
+ cidr_block = "10.20.100.0/24"
# module.vpc.aws_subnet.private["ap-south-1b"] will be created
+ cidr_block = "10.20.101.0/24"
# module.vpc.aws_subnet.public["ap-south-1a"] will be created
+ cidr_block = "10.20.0.0/24"
# module.vpc.aws_subnet.public["ap-south-1b"] will be created
+ cidr_block = "10.20.1.0/24"
I also broke the sandbox CIDR on purpose, 10.99.0.0/33, to check that the module's validation reaches the caller.
Error: Invalid value for variable
on main.tf line 20, in module "vpc":
20: cidr_block = "10.99.0.0/33"
├────────────────
│ var.cidr_block is "10.99.0.0/33"
cidr_block must be a valid IPv4 CIDR, e.g. 10.20.0.0/16.
This was checked by the validation rule at
../../modules/vpc/variables.tf:10,3-13.
The error points at the caller's line and at the rule inside the module. Good error messages in a module actually save the next person a lot of reading.
Versioning with git tags
See, a relative path like ../../modules/vpc means every root always gets the module as it is on disk right now. Change the module for shorty and the sandbox gets the change on its next plan, whether you wanted that or not. For one repo and one person that's OK. Once the module is shared, move it to its own git repo and tag releases.
cd terraform-aws-vpc
git tag v1.0.0
git push origin v1.0.0
Then the callers point at a tag:
module "vpc" {
source = "git::https://github.com/example/terraform-aws-vpc.git?ref=v1.0.0"
name = "sandbox"
cidr_block = "10.99.0.0/16"
azs = ["ap-south-1a"]
}
I tested this with a local git repo (a git::file:// URL instead of GitHub) so I could check it without pushing anywhere. terraform init printed Downloading git::file:///.../gitmod?ref=v1.0.0 for vpc... and copied the module into .terraform/modules/vpc, and validate passed. .terraform/modules/modules.json records the exact source it fetched, which is handy when you're not sure which version a folder is on.
Now shorty can move to v1.1.0 while sandbox stays on v1.0.0 until someone bumps it on purpose. I use semantic versioning for the tags: a new optional variable is a minor version, renaming a variable or removing an output is a major one, because it breaks callers. Bumping the ref, running terraform init and reading the plan is the whole upgrade.
That's it. Write the module for the second project, not the first. Until there are two callers you don't really know which inputs it needs.