Lesson 6 of 8 · 10 min · Structure and safety

Modules: reusable Terraform building blocks

Covers: Terraform 1.17 (local module with for_each). Updated 13 Nov 2026. Part of the DevOps Engineer roadmap.

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 }
}
  • source says where the code is. After adding or changing a module call, run terraform init (it prints Initializing modules... - service_conf in modules/config_file).
  • Arguments are the module's input variables. Module outputs are read as module.NAME.OUTPUT.
  • count and for_each work on modules. With local.services containing web and api, 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

  1. Small, focused interface. Expose the decisions callers must make and give everything else a good default. Thirty required variables defeat the point.
  2. Describe and type every variable and output. description, type, and validation for the dangerous ones.
  3. Secure by default (encryption on, public access off) and make insecure choices explicit.
  4. One responsibility. A "network" module and an "application" module, not a module that creates the whole company.
  5. Compose, don't nest deeply. Modules calling modules calling modules become unreadable. Prefer a flat composition in the root module.
  6. Outputs for what callers need (ids, ARNs, endpoints), not everything.
  7. Do not bake in environment names or account ids; take them as inputs.
  8. Backwards compatibility: renaming a resource inside a module destroys and recreates it for every user. Use moved blocks inside the module when you refactor so existing users' state migrates (next lesson). Follow semantic versioning: breaking interface changes mean a major version.
  9. Document with an example in examples/; the example is also your test.
  10. 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 validate and fmt in CI for every module.
  • terraform test (built in since 1.6): .tftest.hcl files with run blocks, command = plan (fast, no real resources) or apply (creates and destroys real resources), and assert conditions. 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 test with apply) 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 moved blocks, destroying infrastructure for all users.
  • Nesting modules deeply.
  • Using count/for_each over a list of module inputs with unstable ordering.
  • Treating community modules as trusted without reading what they create.

Try it yourself

  1. Extract three similar resources from one of your configurations into a module with variables and outputs, and call it from the root.
  2. Call it with for_each over a map of three entries, then remove one and read the plan.
  3. Pin a registry module with a version constraint and run terraform init; look at .terraform/modules/.
  4. Write a terraform test file 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 with moved blocks.

Going deeper

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.