Skip to Content

Terraform Field Guide · Chapter 6 of 12

Modules: write it once

The second time you write the same load balancer, alarms and log group, stop and make a module. A module is just a folder of Terraform with inputs and outputs. Learn to write one, call it, version it, and ship a change to it without surprising production.

  • 50 min
  • Intermediate
  • Hands-on
  • Free

By , founding engineer running Terraform in production. Updated .

envs/devref=v1.4.0envs/stagingref=v1.4.0envs/prodref=v1.3.0modules/serviceinputs → resources → outputsaws_ecs_serviceaws_lb_target_groupaws_cloudwatch_log_groupaws_cloudwatch_metric_alarmoutputsurlservice_arnprod stays on v1.3.0until dev and staginghave tried v1.4.0
The chapter in one pictureWrite the service once as a module. Each environment calls it with its own inputs and its own pinned version.

By the end you can

0 of 5

What a module is

A module is a folder of .tf files. That is the whole definition. The folder you run terraform apply in is the root module; any other folder you call from it with a module block is a child module.

Think of it as a function. Variables are its parameters, resources are its body, outputs are its return values. You write "a service with its log group and its CPU alarm" once, then call it for the shop, the admin panel and the API, with different names and sizes.

Write one

A conventional module has three files. The inputs:

modules/service/variables.tf
variable "name" {
  type        = string
  description = "Service name, used in every resource name."
}

variable "cpu" {
  type    = number
  default = 256
}

variable "desired_count" {
  type    = number
  default = 1
}

variable "subnet_ids" {
  type = list(string)
}

variable "alarm_topic_arn" {
  type        = string
  description = "SNS topic that receives this service's alarms."
}
Required: every service must have a name.
Sensible defaults mean most callers set only what is different about them.
The module does not create the SNS topic. It is shared, so the caller passes it in.

And the body, with its outputs:

modules/service/main.tf
resource "aws_cloudwatch_log_group" "this" {
  name              = "/ecs/${var.name}"
  retention_in_days = 30
}

resource "aws_ecs_service" "this" {
  name          = var.name
  desired_count = var.desired_count
  # task definition, cluster and network settings
}

resource "aws_cloudwatch_metric_alarm" "cpu_high" {
  alarm_name    = "${var.name}-cpu-high"
  threshold     = 80
  alarm_actions = [var.alarm_topic_arn]
  # metric, period, dimensions
}

output "service_name" {
  value = aws_ecs_service.this.name
}

output "log_group" {
  value = aws_cloudwatch_log_group.this.name
}
A common convention when a module has one resource of a type. Inside a module, the module's name gives the context.
A decision made once for every service. Nobody forgets log retention again.
Every service gets an alarm by default. This is what a module is for: the defaults you want everywhere.
The public interface. Callers can read these and nothing else.

Call it

main.tf
module "shop" {
  source = "git::https://github.com/acme/terraform-modules.git//service?ref=v1.3.0"

  name            = "shop"
  desired_count   = 3
  cpu             = 512
  subnet_ids      = module.network.private_subnet_ids
  alarm_topic_arn = aws_sns_topic.alerts.arn
}

module "admin" {
  source = "git::https://github.com/acme/terraform-modules.git//service?ref=v1.3.0"

  name            = "admin"
  subnet_ids      = module.network.private_subnet_ids
  alarm_topic_arn = aws_sns_topic.alerts.arn
}
A local name for this instance of the module. Its resources get addresses like module.shop.aws_ecs_service.this.
The service folder inside the repository, at tag v1.3.0. The double slash separates the repository from the folder.
One module's output feeding another's input. This is how you build an environment from parts.
The same module again, with defaults for CPU and count.

After adding or changing a module block, run terraform init so Terraform can fetch it. The plan then shows every resource under its module address, for example module.shop.aws_cloudwatch_metric_alarm.cpu_high.

Sources and versions

SourceExampleVersioned by
Local path./modules/serviceNothing: always what is on disk
Gitgit::https://…/modules.git//service?ref=v1.3.0A tag or commit in ref
Terraform Registryterraform-aws-modules/vpc/awsThe version argument
Private registryapp.terraform.io/acme/service/awsThe version argument

Public modules can save you weeks. The community VPC module, for example, builds subnets, route tables and NAT gateways from a dozen lines:

network.tf
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "~> 6.0"

  name = "main"
  cidr = "10.0.0.0/16"
  azs  = ["eu-west-1a", "eu-west-1b", "eu-west-1c"]

  private_subnets = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
  public_subnets  = ["10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24"]
}
Pin it like a provider. Read the changelog before a major version bump.
One private and one public subnet per availability zone, from the lists below.

Read a public module's code before you depend on it. You are taking on its defaults, its bugs and its upgrade path.

Good module design

  • Small and opinionated. A module that wraps a service with its logs and alarms is easy to reuse. A module that exposes every provider argument is just the provider with extra steps.
  • Inputs are what differs. Names, sizes and counts are variables. Things that should be the same everywhere, like log retention and encryption, are not.
  • No providers inside. Let the caller configure the provider (region, account, credentials), so the same module works in every environment.
  • Shallow nesting. A module calling a module calling a module is hard to debug. One or two levels is plenty.

Shipping a change

Shared modules have a cost: one change reaches every caller. This change looks harmless (encryption, and a tidier log group name), but renaming a log group forces a replacement, which deletes its logs. See where it lands:

Interactive · Shipping a module change

You change modules/service. Which environments does it reach?

The change, released as v1.4.0

  • ~ bucket encryption: AES256 → KMS key
  • ~ log group "/ecs/shop" → "/aws/ecs/shop"

Hands-on: build a module

A tiny "static site" module using the local provider, called twice. Create this folder layout:

Layout
mkdir -p modules/site
.
├── main.tf
└── modules/
    └── site/
        └── main.tf
modules/site/main.tf
variable "name" {
  type = string
}

variable "pages" {
  type    = list(string)
  default = ["index"]
}

resource "local_file" "page" {
  for_each = toset(var.pages)
  filename = "${path.root}/sites/${var.name}/${each.key}.html"
  content  = "<h1>${var.name}: ${each.key}</h1>"
}

output "url" {
  value = "file://${abspath(path.root)}/sites/${var.name}/index.html"
}
One file per page, keyed by name. Chapter 8 explains why for_each beats count here.
The root module's folder. Inside a module, path.module would point at modules/site instead.
What callers get back.
main.tf
terraform {
  required_providers {
    local = { source = "hashicorp/local", version = "~> 2.5" }
  }
}

module "blog" {
  source = "./modules/site"
  name   = "blog"
  pages  = ["index", "about", "archive"]
}

module "docs" {
  source = "./modules/site"
  name   = "docs"
}

output "urls" {
  value = [module.blog.url, module.docs.url]
}
A local path. Fine inside one repository; pin versions once modules are shared between repositories.
Same module, only the defaults: one index page.
Reading a module output.
Apply
terraform init
terraform apply -auto-approve
terraform state list
Initializing modules...
- blog in modules/site
- docs in modules/site
...
Apply complete! Resources: 4 added, 0 changed, 0 destroyed.

module.blog.local_file.page["about"]
module.blog.local_file.page["archive"]
module.blog.local_file.page["index"]
module.docs.local_file.page["index"]
Initializing modules
init registers every module call. Run it again whenever you add one.
module.blog.local_file.page["about"]
Module resources are addressed through the module's name.

Mini mission

Give the module a new feature, safely

Add an optional footer variable to the module (default: empty) that is appended to every page. Use it in blog only. Before applying, predict: which files will the plan replace, and which will it leave alone?

Reveal one safe solution
modules/site/main.tf
variable "footer" {
  type    = string
  default = ""
}

resource "local_file" "page" {
  for_each = toset(var.pages)
  filename = "${path.root}/sites/${var.name}/${each.key}.html"
  content  = "<h1>${var.name}: ${each.key}</h1>${var.footer}"
}

The plan replaces the three blog pages and leaves the docs page alone: docs uses the default, an empty footer, so its content is unchanged. That is the pattern for every module change: add the feature behind an input whose default keeps today's behaviour, and existing callers see no changes.

Check yourself

Quiz

0 of 5 answered

  1. 1. What is a Terraform module?
  2. 2. How does the calling code get a value out of a module?
  3. 3. Every environment uses source = "../modules/service". You merge a change to that module. Whose next plan changes?
  4. 4. Which module is the better design?
  5. 5. Why add ?ref=v1.3.0 to a Git module source?

Further reading