Terraform Tutorial · Modules and Quality · Lesson 23 of 25

Terraform Testing

Test modules with terraform test: write .tftest.hcl files with run blocks and assertions, plan-only tests and mocked providers.

terraform test

Since Terraform 1.6, terraform test runs *.tftest.hcl files. Each run block plans or applies the module and checks assert conditions.

# tests/naming.tftest.hcl
variables {
  project     = "shop"
  environment = "prod"
}

run "bucket_name_follows_convention" {
  command = plan

  assert {
    condition     = output.bucket_name == "shop-prod-assets"
    error_message = "Unexpected bucket name"
  }
}
terraform test

Mocking providers

Since 1.7, mock_provider "aws" {} lets tests run without cloud credentials: resources get fake computed values, so you can test logic (naming, counts, conditions) quickly in CI.

What to test

  • Naming conventions and tags
  • Conditional logic (count, for_each, environment switches)
  • Variable validation (use expect_failures to test that bad input is rejected)
  • Integration tests that really apply into a sandbox account, run less often
A module and its test (applied here to show the default output)
# file: main.tf
variable "environment" {
  default = "dev"
}

output "replicas" {
  value = var.environment == "prod" ? 3 : 1
}
# file: replicas.tftest.hcl
run "prod_has_three" {
  command = plan
  variables {
    environment = "prod"
  }
  assert {
    condition     = output.replicas == 3
    error_message = "prod should run 3 replicas"
  }
}

Output

replicas = 1

Run this on your computer — see “Get Started” for setup.

Test yourself

Which file extension does terraform test read?

  1. .tf
  2. .tfvars
  3. .tftest.hcl
  4. .hcl.test
Show answer

Answer: .tftest.hcl