DevOps.Academy
CoursesCurriculumInterview prepPricing
◔My learningSign in
DevOps.Academy

Free, hands-on DevOps lessons. Made with care in India.

System status

Learn

All coursesLinux roadmapCurriculumInterview questionsCheat sheetsMy learning

Academy

PricingCertificates

Legal

PrivacyTermsContact

devops.rajeev.pro

TerraformLesson 10 of 17
Your progress · 0%
On this page
  1. Why modules exist
  2. Root and child modules
  3. Module inputs and outputs
  4. Registry modules
  5. Versioning modules
↖ Course roadmap
Lesson 10 · Modules

Modules: reusable infrastructure

Stop copy-pasting: write a child module with inputs and outputs, call it several times, use a public module from the Terraform Registry, and version modules so upgrades are safe.

30 min read · intermediate · hands-on

By the end of this lesson you'll be able to

0 of 5 complete
Lab status

Verified lab: the local module called twice and the cloudposse/label/null registry module. Run on Terraform 1.17.1; the output shown is real.
Code walkthrough: Git module sources and version tags: explained, not run.
Cloud lab: none; nothing here needs a cloud account.

Why modules exist

Modules are how Terraform code grows past one folder without turning into copy-paste. It helps to see what happens without them.

The problem: one fix, three copies

A team builds a web stack in dev/. It works, so they copy the folder to staging/ and prod/. Months later, a security review says "encrypt the storage". They fix dev, then staging, and miss prod, the one that mattered.

With copies, every fix has to be made in every copy.© Animation: DevOps Academy

With copies, every fix has to be made in every copy.© Animation: DevOps Academy

The fix: write it once, call it with different inputs

A module is a folder of Terraform code with inputs (variables) and outputs, like a function. Each environment calls it with its own values, and a fix to the module reaches every caller.

Inputs in, resources inside, outputs out.© Animation: DevOps Academy

Inputs in, resources inside, outputs out.© Animation: DevOps Academy

And then: versions, so a change doesn't hit production first

Once many configurations use a module, a change to it is a release. Each caller pins a version and upgrades when it's ready: dev first, then staging, then prod.

Pinned versions turn a module change into a normal, staged release.© Animation: DevOps Academy

Pinned versions turn a module change into a normal, staged release.© Animation: DevOps Academy

In this lesson you'll write a module, call it twice, use a real module from the Terraform Registry, and pin versions.

Root and child modules

Every Terraform configuration is a module. The folder you run terraform plan in is the root module. A module it calls with a module block is a child module. A typical layout:

project/
├── main.tf             # root module: calls the child modules
├── outputs.tf
└── modules/
    └── site/           # child module
        ├── main.tf
        ├── variables.tf
        └── outputs.tf

When to write a module: when the same group of resources appears in several places (a VPC, a service with its load balancer and alarms), or to give other teams a safe, opinionated building block. When not to: a module that wraps a single resource and passes every argument through adds a layer and saves nothing.

Module inputs and outputs

The child module from the lab creates one HTML file per page:

# modules/site/variables.tf
variable "name" {
  description = "Site name, used in file names."
  type        = string
}

variable "pages" {
  description = "Page names to create."
  type        = list(string)
  default     = ["index"]
}
# modules/site/main.tf
terraform {
  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "~> 2.9"
    }
  }
}

resource "local_file" "page" {
  for_each = toset(var.pages)

  filename = "${path.root}/out/${var.name}/${each.key}.html"
  content  = "<h1>${var.name}: ${each.key}</h1>\n"
}
# modules/site/outputs.tf
output "files" {
  description = "Paths of the pages this module created."
  value       = [for p in local_file.page : p.filename]
}

The module declares which providers it needs, but has no provider block: configuring providers is the root module's job, and the child inherits them. path.root points at the root folder, so the files land in one out/ regardless of where the module lives.

The root calls it twice with different inputs:

# main.tf
module "shop" {
  source = "./modules/site"
  name   = "shop"
  pages  = ["index", "cart", "checkout"]
}

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

output "shop_files" {
  value = module.shop.files
}

Every module block needs source. The other arguments are the module's variables. blog doesn't pass pages, so it gets the default ["index"]. Outputs are read as module.<name>.<output>.

The resources get addresses that include the module, so the two calls never clash:

$ terraform state list
module.blog.local_file.page["index"]
module.shop.local_file.page["cart"]
module.shop.local_file.page["checkout"]
module.shop.local_file.page["index"]
$ find out -type f | sort
out/blog/index.html
out/shop/cart.html
out/shop/checkout.html
out/shop/index.html
terraform state list
  • terraforminfrastructure as code
find out -type f | sort
  • findsearch for files
  • -typef for files, d for directories
  • |pipe: send output to the next command
  • sortsort lines

Registry modules

The Terraform Registry also hosts modules: thousands of them, including the widely used terraform-aws-modules collection (VPC, EKS, RDS and more). The lab used cloudposse/label/null, which builds consistent resource names and tags and needs no cloud account:

module "label" {
  source    = "cloudposse/label/null"
  version   = "0.25.0"
  namespace = "acme"
  stage     = "prod"
  name      = "shop"
}

output "resource_name" {
  value = module.label.id
}

output "tags" {
  value = module.label.tags
}

A registry source has the form namespace/name/provider. terraform init downloads it:

$ terraform init
Initializing the backend...

Initializing modules...
Downloading registry.terraform.io/cloudposse/label/null 0.25.0 for label...
- label in .terraform/modules/label
- shop in modules/site
- blog in modules/site
...
terraform init
  • terraforminfrastructure as code
  • initdownload providers, set up the folder

Local modules are used in place; registry modules are downloaded into .terraform/modules. The outputs after apply:

resource_name = "acme-prod-shop"
tags = tomap({
  "Name" = "acme-prod-shop"
  "Namespace" = "acme"
  "Stage" = "prod"
})

Before using a public module, check how often it's downloaded and updated, read its inputs, and read its code. You're running someone else's infrastructure code with your credentials.

Versioning modules

SourceExamplePin with
Local path./modules/siteNothing: it's the same commit as the caller
Terraform Registrycloudposse/label/nullversion = "0.25.0" (constraints like ~> 0.25 work)
Gitgit::https://github.com/acme/tf-modules.git//site?ref=v1.3.0?ref= a tag
GitHub shorthandgithub.com/acme/tf-modules//site?ref=v1.3.0?ref= a tag

The //site part points at a subfolder of the repository. The version argument only works for registry sources; Git sources pin with ref, ideally an immutable tag.

For your own shared modules, the workflow looks like any library release:

  1. Keep modules in their own repository, with a README and an examples/ folder.
  2. Release with semantic version tags: v1.3.0. A breaking input change is a major bump.
  3. Each caller pins a tag and upgrades in a pull request: dev first, then staging, then prod.
  4. Run terraform init -upgrade after changing a version, and read the plan.
In production

Keep modules small and focused, with a clear set of inputs and outputs and sensible defaults. Don't configure providers inside them. When you restructure code into modules, use moved blocks (lesson 8) so existing resources move to their new addresses instead of being destroyed and recreated.

⌘
Mini mission

Build a module and call it three times

Write modules/site with variables name and pages, a for_each local_file per page, and a files output. Call it for shop (3 pages), blog (default) and docs (2 pages), add cloudposse/label/null 0.25.0, and output each module's files and the label id.

Input: An empty projectOutput: modules/site/
Reveal one safe solution
$ terraform init
$ terraform apply -auto-approve
$ terraform state list | wc -l
$ terraform output
terraform init
  • terraforminfrastructure as code
  • initdownload providers, set up the folder
terraform apply -auto-approve
  • applymake the changes
  • -auto-approveskip the yes prompt
terraform state list | wc -l
  • |pipe: send output to the next command
  • wccount lines, words and bytes
  • -lcount lines only

You should see 6 page resources in state (3 + 1 + 2) and an id like acme-prod-shop from the label module. If init says "Module not installed", you added a module block without re-running terraform init.

Try it yourself

0 of 5 steps done

Run each task in your own account or terminal, then tick it off.

Knowledge check

Quick check

Question 1 of 4

What is the root module?

Go deeper

Official reading for this lesson

  • DocsModules overviewHashiCorp ↗
  • DocsModule sources (local, registry, Git)HashiCorp ↗
  • GuideModule development best practicesHashiCorp ↗
  • Toolcloudposse/label/null on the Terraform RegistryTerraform Registry ↗
  • Toolterraform-aws-modules (widely used AWS modules)Terraform Registry ↗

Or get every quiz answer right and it completes itself.

Something unclear, wrong or out of date in this lesson? Tell me, and I'll fix it.

← PreviousPlan, apply and destroyNext lesson →Data sources, templates and provisioners