terraform-test
Comprehensive guide for writing and running Terraform tests. Use when creating test files (.tftest.hcl), writing test scenarios with run blocks, validating…
от eric861129★ 52 звезды на GitHub
Установить terraform-test в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
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
testblock (configuration settings) - One to many
runblocks (test executions) - Zero to one
variablesblock (input values) - Zero to many
providerblocks (provider configuration) - Zero to many
mock_providerblocks (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 totrue, 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- Eitherapply(default) orplanplan_options- Configure plan behavior (see below)variables- Override test-level variable valuesmodule- Reference alternate modules for testingproviders- Customize provider availabilityassert- Validation conditions (multiple allowed)expect_failures- Specify expected validation failuresstate_key- Manage state file isolation (since v1.9.0)parallel- Enable parallel execution when set totrue(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) orrefresh-onlyrefresh- Boolean, defaults totruereplace- List of resource addresses to replacetarget- 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
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл terraform-test?
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.
Как установить скилл terraform-test?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл terraform-test запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
AnthropicCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
discernment-nudge
AnthropicAfter you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
data-consolidate
AnthropicJoins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
inspection-to-capa
AnthropicRuns the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…