TExcelTAD
Home › Infrastructure as Code: Terraform & OpenTofu › Testing with terraform test & tofu test

Testing with terraform test & tofu test

validate checks that code is well-formed; it can't tell you that the subnets don't overlap, that the bucket is encrypted, or that a bad input is rejected. Both CLIs have a built-in test framework for that: .tftest.hcl files with run blocks that plan or apply the module and assert on the result. Tests live in tests/ (or next to the code) and run with tofu test / terraform test.

hcl
run "name" {
  command = plan              # or apply (the default): creates real resources, destroyed after the file
  variables {                 # inputs for this run
    environment = "prod"
  }
  assert {
    condition     = local_file.config.content == "replicas=3\n"
    error_message = "prod must run 3 replicas"
  }
  expect_failures = [var.environment]   # instead of asserts: this run must fail on these checks
}

Testing a module with local resources

bash · try it yourself
mkdir -p mod/tests && cd mod
cat > main.tf <<'HCL'
variable "environment" {
  type = string
  validation {
    condition     = contains(["dev", "prod"], var.environment)
    error_message = "environment must be dev or prod."
  }
}

locals {
  replicas = var.environment == "prod" ? 3 : 1
}

resource "local_file" "config" {
  filename = "${path.module}/${var.environment}.conf"
  content  = "replicas=${local.replicas}\n"
}

output "replicas" {
  value = local.replicas
}
HCL
cat > tests/config.tftest.hcl <<'HCL'
variables {
  environment = "dev"          # file-level default for every run
}

run "dev_has_one_replica" {
  command = plan
  assert {
    condition     = output.replicas == 1
    error_message = "dev should run one replica, got ${output.replicas}"
  }
}

run "prod_file_is_written" {
  variables {
    environment = "prod"
  }
  assert {
    condition     = local_file.config.content == "replicas=3\n"
    error_message = "unexpected prod config"
  }
}

run "rejects_unknown_environment" {
  command = plan
  variables {
    environment = "qa"
  }
  expect_failures = [var.environment]
}

run "deliberately_wrong" {
  command = plan
  assert {
    condition     = output.replicas == 2
    error_message = "dev should run two replicas (this test is wrong on purpose)"
  }
}
HCL
tofu init >/dev/null
tofu test; echo "exit=$?"
ls
tests/config.tftest.hcl... fail
  run "dev_has_one_replica"... pass
  run "prod_file_is_written"... pass
  run "rejects_unknown_environment"... pass
  run "deliberately_wrong"... fail

Error: Test assertion failed

  on tests/config.tftest.hcl line 34, in run "deliberately_wrong":
  34:     condition     = output.replicas == 2
    ├────────────────
    │ output.replicas is 1
    ├────────────────
    │ Diff:
    │     1 -> 2

dev should run two replicas (this test is wrong on purpose)

Failure! 3 passed, 1 failed.
exit=1
main.tf
tests
  • Runs execute in order and share state within a file: an apply run creates real resources (here, a real file), later runs see them, and everything is destroyed when the file finishes, which is why no .conf file is left.
  • command = plan runs are fast and create nothing; use them for logic. Use apply when you need values that only exist after creation.
  • expect_failures turns a failing validation (or precondition, or check) into a passing test, the way to test that bad input is rejected.
  • A failed assertion prints its error_message with the values involved, and test exits non-zero: ready for CI.

Testing AWS code offline: mock providers

Applying a VPC module in a test creates real VPCs, costs money and takes minutes. A mock provider replaces the real one: every resource "applies" instantly, computed attributes get generated fake values, and nothing calls AWS. override_resource and override_data fix specific values when a test depends on them (Terraform 1.7+, OpenTofu 1.8+):

bash · try it yourself
mkdir -p net/tests && cd net
cat > main.tf <<'HCL'
terraform {
  required_providers {
    aws = { source = "hashicorp/aws", version = "~> 6.0" }
  }
}

variable "cidr" {
  type    = string
  default = "10.20.0.0/16"
}

data "aws_availability_zones" "available" {
  state = "available"
}

locals {
  azs = slice(data.aws_availability_zones.available.names, 0, 2)
}

resource "aws_vpc" "this" {
  cidr_block = var.cidr
}

resource "aws_subnet" "private" {
  for_each          = { for i, az in local.azs : az => i }
  vpc_id            = aws_vpc.this.id
  availability_zone = each.key
  cidr_block        = cidrsubnet(var.cidr, 8, each.value)
}

output "vpc_id" {
  value = aws_vpc.this.id
}

output "subnet_cidrs" {
  value = sort([for s in aws_subnet.private : s.cidr_block])
}
HCL
cat > tests/network.tftest.hcl <<'HCL'
mock_provider "aws" {
  override_data {
    target = data.aws_availability_zones.available
    values = {
      names = ["eu-west-1a", "eu-west-1b", "eu-west-1c"]
    }
  }
}

override_resource {
  target = aws_vpc.this
  values = {
    id = "vpc-0123456789abcdef0"
  }
}

run "two_private_subnets_in_two_zones" {
  assert {
    condition     = output.subnet_cidrs == tolist(["10.20.0.0/24", "10.20.1.0/24"])
    error_message = "unexpected subnet CIDRs: ${jsonencode(output.subnet_cidrs)}"
  }
  assert {
    condition     = toset(keys(aws_subnet.private)) == toset(["eu-west-1a", "eu-west-1b"])
    error_message = "subnets should use the first two zones"
  }
  assert {
    condition     = aws_subnet.private["eu-west-1a"].vpc_id == "vpc-0123456789abcdef0"
    error_message = "subnets must belong to the module's VPC"
  }
}
HCL
tofu init >/dev/null
echo "=== tofu test"
tofu test
rm -rf .terraform .terraform.lock.hcl && terraform init >/dev/null
echo "=== terraform test"
terraform test
=== tofu test
tests/network.tftest.hcl... pass
  run "two_private_subnets_in_two_zones"... pass

Success! 1 passed, 0 failed.
=== terraform test
tests/network.tftest.hcl... in progress
  run "two_private_subnets_in_two_zones"... pass
tests/network.tftest.hcl... tearing down
tests/network.tftest.hcl... pass

Success! 1 passed, 0 failed.

The same test file runs under both CLIs; Terraform additionally prints the file's start ("in progress") and clean-up ("tearing down") steps. The data.aws_availability_zones lookup, the VPC id and everything else came from the mocks, so the test runs in seconds with no credentials. Without overrides, mocked computed strings are random, so assert only on values you control.

Note: The tolist(...) in the first assertion matters. ["a", "b"] is a tuple literal and the output is a list(string); == compares types too, so without the conversion the assertion fails even though the elements match (Terraform even prints "LHS and RHS values are of different types").

What to test

Test Example
input validation bad CIDR, unknown environment rejected (expect_failures)
derived values subnet maths, names, tags, counts per environment
secure defaults encrypted == true, public access blocked, deletion protection on in prod
conditionals enable_nat = false creates zero NAT gateways
examples run blocks with module { source = "./examples/basic" } prove the documented example works

Mocks test your logic, not AWS: they can't tell you that a CIDR overlaps an existing VPC or that an instance type is not offered in a region. Teams add a smaller set of real apply tests (in a sandbox account, on a schedule or before releasing a module version) for that. Run tofu test -filter=tests/network.tftest.hcl to run one file, -verbose to print each run's plan.

Test yourself

What happens to resources created by apply runs in a test file?

  1. They stay until you run destroy
  2. They are destroyed automatically when the test file finishes
  3. They are imported into your main state
  4. Nothing is ever created

How do you test that a variable's validation rejects bad input?

  1. An assert with condition = false
  2. A run with the bad value and expect_failures = [var.name]
  3. tofu validate -strict
  4. It can't be tested

What does mock_provider "aws" {} give you?

  1. A local AWS emulator
  2. A fake AWS provider: resources apply instantly with generated values and no API calls
  3. Free AWS credits
  4. Real resources in a sandbox account