🎓 A1Learner
🔍
0 of 50 lessons completed

Test Your Configuration

A test is a check that runs against a config before it reaches the cloud. terraform test runs those checks from a .tftest.hcl file.

Mock the provider

The mock provider pretends to be AWS. No real resource is created.

mock_provider "aws" {}

Write one assertion

The run block plans the config. The assert checks the bucket name.

run "bucket_name_is_valid" {
  command = plan

  assert {
    condition     = aws_s3_bucket.app.bucket == "test-bucket-12345"
    error_message = "Bucket name did not match the expected name."
  }
}

Run the test

One command runs every check in the file. A pass is printed for each passing file.

terraform test

Example

# main.tf
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}

variable "bucket_name" {
  type    = string
  default = "test-bucket-12345"
}

resource "aws_s3_bucket" "app" {
  bucket = var.bucket_name
}

# main.tftest.hcl
mock_provider "aws" {}

run "bucket_name_is_valid" {
  command = plan

  assert {
    condition     = aws_s3_bucket.app.bucket == "test-bucket-12345"
    error_message = "Bucket name did not match the expected name."
  }
}

# terraform init
# terraform test

Key points

  • A test catches a wrong name or a missing setting early.
  • A .tftest.hcl file holds run blocks, one per check.
  • Each run block has an assert with a condition and an error message.
  • A mock provider stands in for the real cloud.
  • Mocked tests need no cloud account and no network.

The test file mocks the provider, so no cloud is touched. The run block plans the config and checks the bucket name. A pass means the config behaves as written.

Note

A passing test proves the config, not the live cloud.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

What does terraform test do?