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.
By the end of this lesson you'll be able to
0 of 5 completeVerified 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.
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.
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.
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 listterraforminfrastructure as code
find out -type f | sortfindsearch for files-typef for files, d for directories|pipe: send output to the next commandsortsort 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 initterraforminfrastructure as codeinitdownload 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
| Source | Example | Pin with |
|---|---|---|
| Local path | ./modules/site | Nothing: it's the same commit as the caller |
| Terraform Registry | cloudposse/label/null | version = "0.25.0" (constraints like ~> 0.25 work) |
| Git | git::https://github.com/acme/tf-modules.git//site?ref=v1.3.0 | ?ref= a tag |
| GitHub shorthand | github.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:
- Keep modules in their own repository, with a README and an
examples/folder. - Release with semantic version tags:
v1.3.0. A breaking input change is a major bump. - Each caller pins a tag and upgrades in a pull request: dev first, then staging, then prod.
- Run
terraform init -upgradeafter changing a version, and read the plan.
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.
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.
modules/site/Reveal one safe solution
$ terraform init $ terraform apply -auto-approve $ terraform state list | wc -l $ terraform output
terraform initterraforminfrastructure as codeinitdownload providers, set up the folder
terraform apply -auto-approveapplymake the changes-auto-approveskip the yes prompt
terraform state list | wc -l|pipe: send output to the next commandwccount 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 doneRun each task in your own account or terminal, then tick it off.
Quick check
What is the root module?
Official reading for this lesson
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.