terraform-test

0
1
Source

Comprehensive guide for writing and running Terraform tests. Use when creating test files (.tftest.hcl), writing test scenarios with run blocks, validating infrastructure behavior with assertions, mocking providers and data sources, testing module outputs and resource configurations, or troubleshooting Terraform test syntax and execution.

Install

mkdir -p .claude/skills/terraform-test && curl -L -o skill.zip "https://mcp.directory/api/skills/download/5157" && unzip -o skill.zip -d .claude/skills/terraform-test && rm skill.zip

Installs to .claude/skills/terraform-test

About this skill

Terraform Test

Terraform's built-in testing framework enables module authors to validate that configuration updates don't introduce breaking changes. Tests execute against temporary resources, protecting existing infrastructure and state files.

Core Concepts

Test File: A .tftest.hcl or .tftest.json file containing test configuration and run blocks that validate your Terraform configuration.

Test Block: Optional configuration block that defines test-wide settings (available since Terraform 1.6.0).

Run Block: Defines a single test scenario with optional variables, provider configurations, and assertions. Each test file requires at least one run block.

Assert Block: Contains conditions that must evaluate to true for the test to pass. Failed assertions cause the test to fail.

Mock Provider: Simulates provider behavior without creating real infrastructure (available since Terraform 1.7.0).

Test Modes: Tests run in apply mode (default, creates real infrastructure) or plan mode (validates logic without creating resources).

File Structure

Terraform test files use the .tftest.hcl or .tftest.json extension and are typically organized in a tests/ directory. Use clear naming conventions to distinguish between unit tests (plan mode) and integration tests (apply mode):

my-module/
├── main.tf
├── variables.tf
├── outputs.tf
└── tests/
    ├── validation_unit_test.tftest.hcl      # Unit test (plan mode)
    ├── edge_cases_unit_test.tftest.hcl      # Unit test (plan mode)
    └── full_stack_integration_test.tftest.hcl  # Integration test (apply mode - creates real resources)

Test File Components

A test file contains:

  • Zero to one test block (configuration settings)
  • One to many run blocks (test executions)
  • Zero to one variables block (input values)
  • Zero to many provider blocks (provider configuration)
  • Zero to many mock_provider blocks (mock provider data, since v1.7.0)

Important: The order of variables and provider blocks doesn't matter. Terraform processes all values within these blocks at the beginning of the test operation.

Test Configuration (.tftest.hcl)

Test Block

The optional test block configures test-wide settings:

test {
  parallel = true  # Enable parallel execution for all run blocks (default: false)
}

Test Block Attributes:

  • parallel - Boolean, when set to true, enables parallel execution for all run blocks by default (default: false). Individual run blocks can override this setting.

Run Block

Each run block executes a command against your configuration. Run blocks execute sequentially by default.

Basic Integration Test (Apply Mode - Default):

run "test_instance_creation" {
  command = apply

  assert {
    condition     = aws_instance.example.id != ""
    error_message = "Instance should be created with a valid ID"
  }

  assert {
    condition     = output.instance_public_ip != ""
    error_message = "Instance should have a public IP"
  }
}

Unit Test (Plan Mode):

run "test_default_configuration" {
  command = plan

  assert {
    condition     = aws_instance.example.instance_type == "t2.micro"
    error_message = "Instance type should be t2.micro by default"
  }

  assert {
    condition     = aws_instance.example.tags["Environment"] == "test"
    error_message = "Environment tag should be 'test'"
  }
}

Run Block Attributes:

  • command - Either apply (default) or plan
  • plan_options - Configure plan behavior (see below)
  • variables - Override test-level variable values
  • module - Reference alternate modules for testing
  • providers - Customize provider availability
  • assert - Validation conditions (multiple allowed)
  • expect_failures - Specify expected validation failures
  • state_key - Manage state file isolation (since v1.9.0)
  • parallel - Enable parallel execution when set to true (since v1.9.0)

Plan Options

The plan_options block configures plan command behavior:

run "test_refresh_only" {
  command = plan

  plan_options {
    mode    = refresh-only  # "normal" (default) or "refresh-only"
    refresh = true           # boolean, defaults to true
    replace = [
      aws_instance.example
    ]
    target = [
      aws_instance.example
    ]
  }

  assert {
    condition     = aws_instance.example.instance_type == "t2.micro"
    error_message = "Instance type should be t2.micro"
  }
}

Plan Options Attributes:

  • mode - normal (default) or refresh-only
  • refresh - Boolean, defaults to true
  • replace - List of resource addresses to replace
  • target - List of resource addresses to target

Variables Block

Define variables at the test file level (applied to all run blocks) or within individual run blocks.

Important: Variables defined in test files take the highest precedence, overriding environment variables, variables files, or command-line input.

File-Level Variables:

# Applied to all run blocks
variables {
  aws_region    = "us-west-2"
  instance_type = "t2.micro"
  environment   = "test"
}

run "test_with_file_variables" {
  command = plan

  assert {
    condition     = var.aws_region == "us-west-2"
    error_message = "Region should be us-west-2"
  }
}

Run Block Variables (Override File-Level):

variables {
  instance_type = "t2.small"
  environment   = "test"
}

run "test_with_override_variables" {
  command = plan

  # Override file-level variables
  variables {
    instance_type = "t3.large"
  }

  assert {
    condition     = var.instance_type == "t3.large"
    error_message = "Instance type should be overridden to t3.large"
  }
}

Variables Referencing Prior Run Blocks:

run "setup_vpc" {
  command = apply
}

run "test_with_vpc_output" {
  command = plan

  variables {
    vpc_id = run.setup_vpc.vpc_id
  }

  assert {
    condition     = var.vpc_id == run.setup_vpc.vpc_id
    error_message = "VPC ID should match setup_vpc output"
  }
}

Assert Block

Assert blocks validate conditions within run blocks. All assertions must pass for the test to succeed.

Syntax:

assert {
  condition     = <expression>
  error_message = "failure description"
}

Resource Attribute Assertions:

run "test_resource_configuration" {
  command = plan

  assert {
    condition     = aws_s3_bucket.example.bucket == "my-test-bucket"
    error_message = "Bucket name should match expected value"
  }

  assert {
    condition     = aws_s3_bucket.example.versioning[0].enabled == true
    error_message = "Bucket versioning should be enabled"
  }

  assert {
    condition     = length(aws_s3_bucket.example.tags) > 0
    error_message = "Bucket should have at least one tag"
  }
}

Output Validation:

run "test_outputs" {
  command = plan

  assert {
    condition     = output.vpc_id != ""
    error_message = "VPC ID output should not be empty"
  }

  assert {
    condition     = length(output.subnet_ids) == 3
    error_message = "Should create exactly 3 subnets"
  }
}

Referencing Prior Run Block Outputs:

run "create_vpc" {
  command = apply
}

run "validate_vpc_output" {
  command = plan

  assert {
    condition     = run.create_vpc.vpc_id != ""
    error_message = "VPC from previous run should have an ID"
  }
}

Complex Conditions:

run "test_complex_validation" {
  command = plan

  assert {
    condition = alltrue([
      for subnet in aws_subnet.private :
      can(regex("^10\\.0\\.", subnet.cidr_block))
    ])
    error_message = "All private subnets should use 10.0.0.0/8 CIDR range"
  }

  assert {
    condition = alltrue([
      for instance in aws_instance.workers :
      contains(["t2.micro", "t2.small", "t3.micro"], instance.instance_type)
    ])
    error_message = "Worker instances should use approved instance types"
  }
}

Expect Failures Block

Test that certain conditions intentionally fail. The test passes if the specified checkable objects report an issue, and fails if they do not.

Checkable objects include: Input variables, output values, check blocks, and managed resources or data sources.

run "test_invalid_input_rejected" {
  command = plan

  variables {
    instance_count = -1
  }

  expect_failures = [
    var.instance_count
  ]
}

Testing Custom Conditions:

run "test_custom_condition_failure" {
  command = plan

  variables {
    instance_type = "t2.nano"  # Invalid type
  }

  expect_failures = [
    var.instance_type
  ]
}

Module Block

Test a specific module rather than the root configuration.

Supported Module Sources:

  • Local modules: ./modules/vpc, ../shared/networking
  • Public Terraform Registry: terraform-aws-modules/vpc/aws
  • Private Registry (HCP Terraform): app.terraform.io/org/module/provider

Unsupported Module Sources:

  • ❌ Git repositories: git::https://github.com/...
  • ❌ HTTP URLs: https://example.com/module.zip
  • ❌ Other remote sources (S3, GCS, etc.)

Module Block Attributes:

  • source - Module source (local path or registry address)
  • version - Version constraint (only for registry modules)

Testing Local Modules:

run "test_vpc_module" {
  command = plan

  module {
    source = "./modules/vpc"
  }

  variables {
    cidr_block = "10.0.0.0/16"
    name       = "test-vpc"
  }

  assert {
    condition     = aws_vpc.main.cidr_block == "10.0.0.0/16"
    error_message = "VPC CIDR should match input variable"
  }
}

Testing Public Registry Modules:

run "test_registry_module" {
  command = plan

  module {
    source  = "terraform-aws-modules/vpc/aws"
    version = "5.0.0"
  }

  variables {
    name = "test-vpc"
    cidr = "10.0.0.0/16"
  }

  assert {
    condition     = output.vpc_id != ""
    error_message = "VPC should be created"
  }
}

Provider Configuration

Override o


Content truncated.

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

1,5701,369

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

1,1161,190

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

1,4181,109

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

1,193747

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

1,153683

pdf-to-markdown

aliceisjustplaying

Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.

1,311614

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.