Lesson 6 of 8 · 10 min · Structure and safety
Modules: reusable Terraform building blocks
What you will learn
- What a module is and why to use them
- Writing a module: variables in, resources inside, outputs out
- Calling a module, including with
for_each - Local, registry and Git module sources, and versioning
- Design guidelines, testing and common pitfalls
In simple words
When you find yourself copying the same block of Terraform again and again, turn it into a module. A module is like a function: it takes a few inputs, creates a set of resources that belong together, and hands back a few results. Teams build modules for the patterns they repeat.
Words to know
- Module: a reusable package of Terraform code.
- Input: a variable the module accepts.
- Output: a value the module hands back.
- Version pinning: fixing which version of a module you use, so an update can't surprise you.
What a module is
Every Terraform directory is already a module (the root module). A child module is a directory of .tf files that you call from another configuration, like a function in programming: it takes inputs (variables), creates resources and returns outputs. Use modules to:
- avoid repetition: the same "web service" pattern for ten services,
- standardise: one reviewed way to create a VPC or a database with the company's tags, encryption and logging,
- hide complexity: the caller sets five inputs instead of writing sixty lines,
- version and test the pattern separately from its uses.
Anything you would copy and paste between configurations is a candidate for a module; but do not abstract too early (see the guidelines).
Writing a module
A module is just files. Our example, modules/config_file/main.tf, writes a configuration file from a map of settings:
terraform {
required_providers {
local = { source = "hashicorp/local" }
}
}
variable "name" {
type = string
}
variable "settings" {
type = map(string)
default = {}
}
variable "dir" {
type = string
}
locals {
body = join("\n", [for k, v in var.settings : "${k}=${v}"])
}
resource "local_file" "this" {
filename = "${var.dir}/${var.name}.conf"
content = "${local.body}\n"
}
output "path" {
value = local_file.this.filename
}
The interface of a module is its variable and output blocks. The caller sees nothing else: resources and locals are internal. Conventional layout for a real module:
modules/network/
main.tf # resources
variables.tf # inputs, with descriptions and types
outputs.tf # outputs
versions.tf # required_providers / required_version (no provider configuration!)
README.md # what it does, inputs/outputs, an example
Important: do not put provider configuration blocks inside reusable modules; declare only required_providers. The root module configures providers and passes them down. (Otherwise modules become hard to reuse, and removing them gets messy.)
Calling a module
module "service_conf" {
source = "./modules/config_file"
for_each = local.services
name = each.key
dir = "${path.module}/out"
settings = each.value
}
output "paths" {
value = { for k, m in module.service_conf : k => m.path }
}
sourcesays where the code is. After adding or changing a module call, runterraform init(it printsInitializing modules... - service_conf in modules/config_file).- Arguments are the module's input variables. Module outputs are read as
module.NAME.OUTPUT. countandfor_eachwork on modules. Withlocal.servicescontainingwebandapi, the plan created one instance of the module for each:
# module.service_conf["api"].local_file.this will be created
+ filename = "./out/api.conf"
# module.service_conf["web"].local_file.this will be created
+ filename = "./out/web.conf"
The resulting files held port=80 / replicas=3 for web and port=8080 / replicas=2 for api. State addresses include the module path: module.service_conf["web"].local_file.this. Removing api from the services map destroyed only that module instance (one resource), nothing else.
Pass providers explicitly when a module needs a non-default one: providers = { aws = aws.mumbai }.
Module sources and versions
| Source | Example | Notes |
|---|---|---|
| Local path | ./modules/network |
simplest; versioned with the repo |
| Terraform Registry | terraform-aws-modules/vpc/aws with version = "~> 5.0" |
public, versioned; read the code before trusting it |
| Git | git::https://github.com/org/modules.git//network?ref=v1.4.2 |
pin a tag or commit SHA |
| Private registry | HCP Terraform, Artifactory, GitLab registry | internal sharing |
| S3/GCS | archive in a bucket | rare |
Always pin versions (version = "~> 5.0" for registry modules; ?ref=v1.4.2 for Git). An unpinned module can change under you and alter your infrastructure at the next plan. Treat a module upgrade like a provider upgrade: update the version, run init -upgrade, read the plan. Popular community modules (for example terraform-aws-modules/vpc/aws, eks/aws, rds/aws) are well maintained, and are a good base; wrap them in your own thin module if you need to enforce company policies.
Design guidelines
- Small, focused interface. Expose the decisions callers must make and give everything else a good default. Thirty required variables defeat the point.
- Describe and type every variable and output.
description,type, andvalidationfor the dangerous ones. - Secure by default (encryption on, public access off) and make insecure choices explicit.
- One responsibility. A "network" module and an "application" module, not a module that creates the whole company.
- Compose, don't nest deeply. Modules calling modules calling modules become unreadable. Prefer a flat composition in the root module.
- Outputs for what callers need (ids, ARNs, endpoints), not everything.
- Do not bake in environment names or account ids; take them as inputs.
- Backwards compatibility: renaming a resource inside a module destroys and recreates it for every user. Use
movedblocks inside the module when you refactor so existing users' state migrates (next lesson). Follow semantic versioning: breaking interface changes mean a major version. - Document with an example in
examples/; the example is also your test. - Don't over-abstract. A module wrapping a single resource with the same arguments as the resource adds indirection and nothing else. Wait for the third repetition.
Testing modules
terraform validateandfmtin CI for every module.terraform test(built in since 1.6):.tftest.hclfiles withrunblocks,command = plan(fast, no real resources) orapply(creates and destroys real resources), andassertconditions. We ran one: an assertion on the planned bucket name passed (run "name_is_used"... pass) and a deliberately wrong assertion failed with the message "this assertion is meant to fail".- Static analysis: tflint (provider-specific mistakes), checkov, trivy config or tfsec (security misconfigurations), terraform-docs (generates the README tables).
- Apply the example in a sandbox account in CI on changes (Terratest or
terraform testwithapply) for important shared modules.
Common mistakes
- Provider blocks inside modules.
- Unpinned module versions.
- Modules with huge variable lists and no defaults.
- Renaming resources in a module without
movedblocks, destroying infrastructure for all users. - Nesting modules deeply.
- Using
count/for_eachover a list of module inputs with unstable ordering. - Treating community modules as trusted without reading what they create.
Try it yourself
- Extract three similar resources from one of your configurations into a module with variables and outputs, and call it from the root.
- Call it with
for_eachover a map of three entries, then remove one and read the plan. - Pin a registry module with a version constraint and run
terraform init; look at.terraform/modules/. - Write a
terraform testfile with one passing and one failing assertion.
Check yourself
What forms the interface of a module?
Its input variables and its outputs. Everything else (resources, locals) is internal to the module.
Why should reusable modules not contain provider configurations?
The root module should decide which accounts, regions and credentials are used; embedded provider blocks make modules inflexible and difficult to remove or reuse.
Why pin module versions?
An unpinned module can change between runs and alter your infrastructure unexpectedly. Pinning makes changes deliberate and reviewable.
What happens to existing infrastructure if you rename a resource inside a module?
Terraform sees the old address removed and a new one added, so it plans to destroy and recreate it, unless you add a moved block mapping the old address to the new one.
Interview questions
When would you create a module?
When a pattern is repeated across stacks or environments, or when the organisation wants a standardised, secure-by-default way to create something (a VPC, an ECS service, a database), after the pattern has stabilised.
How do you create the same stack in dev, staging and prod?
Call shared modules from per-environment root configurations (or workspaces with care), passing environment-specific variables, with separate state and permissions for each.
How do you test Terraform modules?
Static checks (fmt, validate, tflint, security scanners), terraform test plan/apply tests, and example configurations applied in a sandbox account in CI.
Summary
- A module is a directory of Terraform code with variables (inputs) and outputs; the root module calls child modules, optionally with
count/for_each. - Source modules locally, from the registry or Git, always pinned to versions.
- Keep interfaces small and typed, secure by default, free of provider blocks, composed flatly and documented.
- Test with validate, static analysis and
terraform test; refactor safely withmovedblocks.
Going deeper
- Modules overview: concepts and syntax.
- Module development: structure, composition and best practices.
- Module sources: local paths, registry, Git and more.
- Terraform test: writing
.tftest.hclfiles. - terraform-aws-modules on the registry: widely used community modules.
- tflint and terraform-docs: linting and documentation tools.
See how much of this you can explain
A free mock interview asks you new questions on Infrastructure as Code with Terraform for DevOps Engineer and scores every answer, with what to fix.