Terraform Advanced — Terraform Test Framework

less than 1 minute read

Built-in testing with terraform test (Terraform 1.6+).


File Structure

modules/vpc/
├── main.tf
├── variables.tf
├── outputs.tf
└── tests/
    ├── basic.tftest.hcl
    └── validation.tftest.hcl

Basic Test

# tests/basic.tftest.hcl

variables {
  vpc_cidr     = "10.0.0.0/16"
  environment  = "test"
}

run "creates_vpc" {
  command = plan  # Don't actually create resources

  assert {
    condition     = aws_vpc.main.cidr_block == "10.0.0.0/16"
    error_message = "VPC CIDR did not match expected value"
  }

  assert {
    condition     = aws_vpc.main.tags["Environment"] == "test"
    error_message = "Environment tag not set correctly"
  }
}

Validation Test

# tests/validation.tftest.hcl

run "rejects_invalid_cidr" {
  command = plan

  variables {
    vpc_cidr    = "invalid"
    environment = "dev"
  }

  expect_failures = [var.vpc_cidr]
}

run "rejects_invalid_environment" {
  command = plan

  variables {
    vpc_cidr    = "10.0.0.0/16"
    environment = "banana"
  }

  expect_failures = [var.environment]
}

Running Tests

$ terraform test
tests/basic.tftest.hcl... pass
  run "creates_vpc"... pass
tests/validation.tftest.hcl... pass
  run "rejects_invalid_cidr"... pass
  run "rejects_invalid_environment"... pass

Success! 3 passed, 0 failed.

💡 Production Tip: Use command = plan for fast unit tests. Use command = apply only when you need to verify real API behavior.


What’s Next?

Integration testing with Terratest.

← TFLint & tfsec Terratest →

Updated: