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

Members can save this page, take notes and track progress. See membership · Sign in

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.

Root module (naming-module/)var.environment"dev" ✓ validatedmodule "assets"module "logs"inputsassets, owner platformoutputsname, tags…inputslogs, owner sreoutputsname, tags…local_file.inventoryout/shop-dev.jsonreads module.assets.nameand module.logs.tagsOne module, called twice with different inputs; callers read only its outputs
The root module calls the naming module twice and builds an inventory from its outputs

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

Download starter filesDownload finished project

Steps

  1. 1Module inputs

    A module is just a folder of .tf files. 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"
    }
    
  2. 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"
      }
    }
    
  3. 3Module outputs

    Outputs are the module's return values. Add a description to 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
    }
    
  4. 4Root: pin the provider

    versions.tf
    terraform {
      required_version = ">= 1.6"
    
      required_providers {
        local = {
          source  = "hashicorp/local"
          version = "~> 2.5"
        }
      }
    }
    
  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."
      }
    }
    
  6. 6Call the module twice

    Each module block is one instance with its own inputs. Read its outputs as module.<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 }
      })
    }
    
  7. 7Root outputs

    outputs.tf
    output "names" {
      value = [module.assets.name, module.logs.name]
    }
    
  8. 8Initialise and plan

    init also installs modules: local ones are just linked.

    Run
    terraform init
    terraform plan
    

    Expected 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 has Owner = "sre".

  9. 9Write the tests

    terraform test runs every *.tftest.hcl file in tests/. Each run block plans (or applies) the configuration and checks assert conditions. expect_failures turns "this input must be rejected" into a passing test.

    The file-level variables block sets inputs for every run. Each run block makes a plan in memory (command = plan), so nothing is created, and then checks it: every assert must be true. expect_failures turns a run around: it passes only if the named check (here the var.environment validation) fails, which proves bad input is rejected.

    naming.tftest.hclvariables { env = prod }run names_follow…command = planplan in memoryno real resources2 assertspassrun every_resource…command = planplan in memoryno real resources1 assertpassrun rejects_unknown…environment = qaplan in memoryno real resourcesexpect_failurespass if validation failsterraform test: each run block plans the module and checks the result; 3 passed, 0 failed
    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]
    }
    
  10. 10Run the tests

    Run
    terraform test
    

    Expected 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.
  11. 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 test
    

    Expected 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 test reports 3 passed, 0 failed again.

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 test runs 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

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake