Terraform Labs · Lab 3 of 9
Write a Module and Test It with terraform test
Extract a naming-and-tagging module with validated inputs, call it twice from a root module, and protect the convention with `terraform test`: plan-mode assertions plus a test that bad input is rejected.
- Environment
- Local
- Level
- Intermediate
- Time
- About 45 min
- Cost
- Free
You will build
A reusable naming module that every resource in a company could use, with tests that fail the moment someone
breaks the naming convention.
Before you start
- Lab: Variables, Locals and for_each: One Config per Environment
Terraform 1.6 or newer (for terraform test)
Naming and tagging look trivial until a cost report can't tell which team owns half the bill. A tiny module that every configuration calls fixes that, and tests keep it fixed. The module has no resources, so it's also the simplest possible module to learn on.
How the pieces fit
The root module is the folder you run terraform in. It passes var.environment into two module
calls, assets and logs; each call is a separate instance of modules/naming with its own inputs
(component, and an owner that defaults to platform). Inside the module, locals build the name and
tags, and its outputs (name, prefix, tags) are all a caller can see. local_file.inventory reads
those outputs to write one JSON file.
Project structure
naming-module/
├── .gitignore
├── versions.tf
├── variables.tf
├── main.tf # calls the module twice
├── outputs.tf
├── modules/
│ └── naming/
│ ├── variables.tf # inputs with validation
│ ├── main.tf # the convention, in locals
│ └── outputs.tf # prefix, name, tags
└── tests/
└── naming.tftest.hcl
Steps
-
1Module inputs
A module is just a folder of
.tffiles. Its variables are its inputs; validate them here so every caller gets the same checks.modules/naming/variables.tf variable "project" { description = "Short project name: lowercase letters, digits and hyphens" type = string validation { condition = can(regex("^[a-z][a-z0-9-]{1,20}$", var.project)) error_message = "project must be 2-21 lowercase letters, digits or hyphens, starting with a letter." } } variable "environment" { description = "dev, staging or prod" type = string } variable "component" { description = "What the resource is for, e.g. assets or logs" type = string } variable "owner" { description = "Team that owns the resources" type = string default = "platform" } -
2The convention
modules/naming/main.tf locals { prefix = "${var.project}-${var.environment}" tags = { Project = var.project Environment = var.environment Component = var.component Owner = var.owner ManagedBy = "terraform" } } -
3Module outputs
Outputs are the module's return values. Add a
descriptionto each: it's the module's documentation.modules/naming/outputs.tf output "prefix" { description = "Prefix for every resource name: <project>-<environment>" value = local.prefix } output "name" { description = "Full resource name: <project>-<environment>-<component>" value = "${local.prefix}-${var.component}" } output "tags" { description = "Standard tags for every resource" value = local.tags } -
4Root: pin the provider
versions.tf terraform { required_version = ">= 1.6" required_providers { local = { source = "hashicorp/local" version = "~> 2.5" } } } -
5Root: inputs
variables.tf variable "environment" { description = "dev, staging or prod" type = string default = "dev" validation { condition = contains(["dev", "staging", "prod"], var.environment) error_message = "environment must be dev, staging or prod." } } -
6Call the module twice
Each
moduleblock is one instance with its own inputs. Read its outputs asmodule.<name>.<output>.main.tf module "assets" { source = "./modules/naming" project = "shop" environment = var.environment component = "assets" } module "logs" { source = "./modules/naming" project = "shop" environment = var.environment component = "logs" owner = "sre" } resource "local_file" "inventory" { filename = "${path.module}/out/${module.assets.prefix}.json" content = jsonencode({ assets = { name = module.assets.name, tags = module.assets.tags } logs = { name = module.logs.name, tags = module.logs.tags } }) } -
7Root outputs
outputs.tf output "names" { value = [module.assets.name, module.logs.name] } -
8Initialise and plan
initalso installs modules: local ones are just linked.Run terraform init terraform planExpected output
Initializing modules... - assets in modules/naming - logs in modules/naming ... # local_file.inventory will be created + resource "local_file" "inventory" { + content = jsonencode( { + assets = { + name = "shop-dev-assets" + tags = { + Component = "assets" + Environment = "dev" + ManagedBy = "terraform" + Owner = "platform" + Project = "shop" } } + logs = { + name = "shop-dev-logs" ... + Owner = "sre" ... Plan: 1 to add, 0 to change, 0 to destroy.Check:Both names follow
<project>-<environment>-<component>and logs hasOwner = "sre". -
9Write the tests
terraform testruns every*.tftest.hclfile intests/. Eachrunblock plans (or applies) the configuration and checksassertconditions.expect_failuresturns "this input must be rejected" into a passing test.The file-level
variablesblock sets inputs for every run. Each run block makes a plan in memory (command = plan), so nothing is created, and then checks it: everyassertmust be true.expect_failuresturns a run around: it passes only if the named check (here thevar.environmentvalidation) fails, which proves bad input is rejected.How terraform test runs: each run block makes a plan and checks it with assert or expect_failures tests/naming.tftest.hcl variables { environment = "prod" } run "names_follow_the_convention" { command = plan assert { condition = module.assets.name == "shop-prod-assets" error_message = "Asset name must be <project>-<environment>-<component>." } assert { condition = module.logs.tags["Owner"] == "sre" error_message = "The logs owner should override the default." } } run "every_resource_is_tagged" { command = plan assert { condition = alltrue([for k in ["Project", "Environment", "Owner", "ManagedBy"] : contains(keys(module.assets.tags), k)]) error_message = "Required tags are missing." } } run "rejects_unknown_environment" { command = plan variables { environment = "qa" } expect_failures = [var.environment] } -
10Run the tests
Run terraform testExpected output
tests/naming.tftest.hcl... in progress run "names_follow_the_convention"... pass run "every_resource_is_tagged"... pass run "rejects_unknown_environment"... pass tests/naming.tftest.hcl... tearing down tests/naming.tftest.hcl... pass Success! 3 passed, 0 failed.
-
11Break the convention on purpose
In
modules/naming/main.tf, change the-between project and environment to_, run the tests, then change it back. The diff in the failure tells you exactly what broke.Run terraform testExpected output
run "names_follow_the_convention"... fail Error: Test assertion failed on tests/naming.tftest.hcl line 9, in run "names_follow_the_convention": 9: condition = module.assets.name == "shop-prod-assets" ├──────────────── │ Diff: │ --- actual │ +++ expected │ - "shop_prod-assets" │ + "shop-prod-assets" Asset name must be <project>-<environment>-<component>. ... Failure! 2 passed, 1 failed.Check:After restoring the
-,terraform testreports3 passed, 0 failedagain.
In production
What changes
| In this lab | In production |
|---|---|
Module in ./modules/naming of the same repository |
Shared modules in their own repository or a private registry, released with semantic version tags |
source = "./modules/naming" |
source = "git::https://github.com/acme/tf-modules.git//naming?ref=v1.4.0" or version = "~> 1.4" from a registry |
| Tests run when you remember | terraform test runs in CI on every pull request to the module; a release is only tagged when tests pass |
| Plan-only tests | Plan tests with mock_provider for fast checks, plus a nightly integration test that applies into a sandbox account and destroys |
Module design rules that hold up
- One job per module (naming, a network, a database), with few inputs and good defaults.
- No provider blocks inside reusable modules — the caller configures providers.
- Outputs for everything a caller may need, each with a description.
- Breaking changes bump the major version (renamed inputs, changed naming), so callers upgrade on purpose.
Production checklist
- Every module input has a type, a description and validation where values are constrained
- Modules are versioned and callers pin a version or tag
terraform testruns in CI for every module change- Tests cover the convention, the defaults and rejected input (
expect_failures) - Tags include at least Project, Environment, Owner and ManagedBy, for cost and ownership reports
Learn the concepts
- Terraform Modules · Terraform Tutorial
- Terraform Testing · Terraform Tutorial
- Terraform Validation and Checks · Terraform Tutorial
- Terraform Outputs · Terraform Tutorial
- Terraform in Production · Course
Preparing for the Terraform Associate exam? Practice tests and mock exams →