claude-skill-hcp-terraform / terraform-test
CLAUDE.md4 starsChanged 13 months agoMITView on GitHub
This is a Claude Skill repository for HashiCorp Terraform Test - a specialized knowledge base that provides comprehensive documentation and guidance for writing and running automated tests for Terraform configurations. This is not a traditional software project with executable code, but rather a documentation repository structured as a skill module for Claude AI assistants. Purpose: Enable Claude to help users create test files (.tftest.hcl), write test scenarios with run blocks, validate infrastructure behavior with assertions, mock providers and data sources,…
- Commits and pushes
In this repository8 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- terraform-mcp-as-code/CLAUDE.mdCLAUDE.md
- terraform-stacks/CLAUDE.mdCLAUDE.md
- terraform-style-guide/CLAUDE.mdCLAUDE.md
- Terraform Infrastructure as CodeSkill
- terraform-stacksSkill
- terraform-style-guideSkill
- terraform-testSkill
The file
Show its rules and text
We split this CLAUDE.md into the rules it gives an agent
54 rules. About 0 are common, 31 are distinctive, and 23 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈31
Distinctive · estimate
This author's own choices. Worth a look.
23
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 26
Test file structure and components
- Distinctive: line 27
Test configuration syntax (run, assert, variables, expect_failures, etc.)
- Distinctive: line 29
Test execution commands and options
- Very specific: line 58
Important: When helping users write tests, always clarify which mode is appropriate for their use case.
- Very specific: line 62
Test files (.tftest.hcl or .tftest.json) contain:
- Distinctive: line 73
Run blocks execute sequentially by default:
- Very specific: line 75
Use parallel = true for independent tests (requires different state files)
- Distinctive: line 98
If users have Git-based modules, guide them to either clone locally or publish to a registry.
- Very specific: line 110
Debugging: Use terraform test -no-cleanup to leave resources in place for inspection.
- Very specific: line 117
Create a tests/ directory in their module
- Very specific: line 118
Start with a simple defaults.tftest.hcl testing default configuration
- Very specific: line 119
Use command = plan for fast unit tests
- Very specific: line 120
Add command = apply integration tests for critical paths
- Very specific: line 126
Use command = plan instead of apply where possible
- Distinctive: line 127
Use mock providers (requires Terraform 1.7.0+) for isolated unit tests
- Very specific: line 128
Use parallel = true for independent tests with different state files
- Distinctive: line 130
Run integration tests only in CI, not locally
- Distinctive: line 135
Create multiple run blocks in the same test file
- Very specific: line 137
Use descriptive names: run "test_small_deployment", run "test_large_deployment"
- Distinctive: line 138
Keep related scenarios in the same file for context
- Very specific: line 144
Use mock_provider blocks to simulate provider behavior
- Distinctive: line 152
Test that validation rules work correctly
- Distinctive: line 153
Test that invalid inputs are rejected
- Distinctive: line 155
Test passes when the specified objects fail as expected
- Very specific: line 160
Run terraform test in CI pipeline
- Very specific: line 163
Use -verbose flag for detailed CI output
- Very specific: line 165
Run unit tests (plan mode) on every PR: terraform test tests/*_unit_test.tftest.hcl
- Very specific: line 166
Run integration tests (apply mode) only on merge to main or scheduled: terraform test tests/*_integration_test.tftest.hcl
- Very specific: line 185
Solution: Ensure run blocks are sequential (not parallel) and use correct syntax: run.<block_name>.<output_name>
- Distinctive: line 189
Issue: Test references Git or HTTP module source
- Very specific: line 195
Solution: Use different modules (automatic separate state), state_key attribute, or mock providers for isolation.
- Distinctive: line 219
Use descriptive names that explain the test scenario:
- Distinctive: line 227
Write clear error messages that help diagnose failures:
- Distinctive: line 237
Test default configuration works
- Distinctive: line 240
Test resource counts and attributes
- Distinctive: line 241
Test outputs are defined correctly
- Very specific: line 243
All with command = plan - fast, free, no real resources.
- Very specific: line 253
Use command = apply sparingly - slower, costs money, creates real resources.
- Distinctive: line 260
Test logic without cloud provider calls
- Distinctive: line 268
No compilation or build commands
- Distinctive: line 269
No package manager or dependencies
- Distinctive: line 271
No Docker or containerization
- Distinctive: line 277
Keep examples accurate: - All code examples must use valid Terraform test syntax
- Distinctive: line 279
Test command accuracy: - Ensure all CLI commands are correct
- Distinctive: line 284
Use Git for all changes:
- Distinctive: line 296
All Terraform test examples use HCL syntax:
- Distinctive: line 316
Use these exact terms consistently:
- Distinctive: line 326
Always use the full command format:
- Distinctive: line 386
Always check user's Terraform version if they request features from newer versions.
- Distinctive: line 401
Terraform Test: Start here for most projects
- Very specific: line 414
Use command = plan (validates logic without creating resources)
- Very specific: line 415
Use mock providers with command = plan (requires Terraform 1.7.0+)
- Distinctive: line 420
Test runs in context of your workspace
- Very specific: line 427
Use the module block in run blocks:
≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Project Overview
This is a Claude Skill repository for HashiCorp Terraform Test - a specialized knowledge base that provides comprehensive documentation and guidance for writing and running automated tests for Terraform configurations. This is not a traditional software project with executable code, but rather a documentation repository structured as a skill module for Claude AI assistants.
Purpose: Enable Claude to help users create test files (.tftest.hcl), write test scenarios with run blocks, validate infrastructure behavior with assertions, mock providers and data sources, test module outputs and resource configurations, and troubleshoot Terraform test syntax and execution.
Repository Structure
claude-skill-terraform-test/
├── README.md # Brief project description
├── SKILL.md # Main comprehensive guide
└── CLAUDE.md # This file - guidance for Claude CodeDocumentation Architecture
Core Documentation
SKILL.md - Comprehensive guide covering:
- Core concepts (test files, run blocks, assert blocks, mock providers)
- Test file structure and components
- Test configuration syntax (run, assert, variables, expect_failures, etc.)
- Mock providers for unit testing
- Test execution commands and options
- Common test patterns
- Integration testing
- Cleanup and destruction
- Best practices
- Advanced features (parallel execution, state management)
- Troubleshooting
- Complete example test suite
- CI/CD integration
Key Terraform Test Concepts
Test Modes: Apply vs Plan
Critical Understanding: Terraform tests use two modes:
- Integration Testing (Default):
command = apply- Creates real infrastructure in your cloud provider
- Tests actual resource creation and behavior
- Slower and incurs cloud costs
- Resources are automatically destroyed after test completion
- Best for validating end-to-end infrastructure behavior
- Unit Testing:
command = plan- Does NOT create real infrastructure
- Validates Terraform logic, conditionals, and outputs
- Fast and free (no cloud resources created)
- Best for testing module logic, variable handling, resource counts
Important: When helping users write tests, always clarify which mode is appropriate for their use case. Default is apply, not plan.
Test File Structure
Test files (.tftest.hcl or .tftest.json) contain:
- Zero to one
testblock (configuration settings) - One to many
runblocks (test scenarios) - 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 - they're all processed at the beginning.
Run Block Execution
Run blocks execute sequentially by default:
- Each run block can reference outputs from previous run blocks via
run.<block_name>.<output_name> - Use
parallel = truefor independent tests (requires different state files) - Sequential execution is critical for tests with dependencies
Variable Precedence
Critical: Variables defined in test files have the highest precedence, overriding:
- Environment variables
- Variables files (
.tfvars) - Command-line input (
-var)
This ensures test scenarios are reproducible and not affected by external configuration.
Module Support Limitation
Important: Terraform test files only support:
- Local modules:
./modules/vpcor../shared-modules/networking - Registry modules:
terraform-aws-modules/vpc/awsorapp.terraform.io/my-org/vpc/aws
NOT supported:
- Git sources
- HTTP/HTTPS archives
- Other remote sources
If users have Git-based modules, guide them to either clone locally or publish to a registry.
Cleanup and Destruction
Critical behavior: Resources created with command = apply are destroyed in reverse run block order after test completion.
Why this matters: For resources with dependencies (e.g., S3 bucket with objects), destruction order is critical:
- Objects must be deleted first (later run block)
- Bucket can then be deleted (earlier run block)
The reverse order ensures dependencies are respected during cleanup.
Debugging: Use terraform test -no-cleanup to leave resources in place for inspection.
Common Scenarios and Patterns
When Users Ask "How do I test my module?"
Guide them to:
- Create a
tests/directory in their module - Start with a simple
defaults.tftest.hcltesting default configuration - Use
command = planfor fast unit tests - Add
command = applyintegration tests for critical paths - Organize tests by scenario (defaults, edge cases, integration)
When Users Ask "My tests are too slow"
Suggest:
- Use
command = planinstead ofapplywhere possible - Use mock providers (requires Terraform 1.7.0+) for isolated unit tests
- Use
parallel = truefor independent tests with different state files - Separate slow integration tests from fast unit tests
- Run integration tests only in CI, not locally
When Users Ask About Testing Multiple Scenarios
Guide them to:
- Create multiple run blocks in the same test file
- Override variables in each run block for different scenarios
- Use descriptive names:
run "test_small_deployment",run "test_large_deployment" - Keep related scenarios in the same file for context
When Users Ask About Mocking
Guide them to:
- Requires Terraform 1.7.0 or later
- Use
mock_providerblocks to simulate provider behavior - Define
mock_resourceandmock_datawith default values - Enables fast unit testing without cloud resources
- Best for testing logic in isolation
When Users Ask About Testing Failures
Guide them to use expect_failures:
- Test that validation rules work correctly
- Test that invalid inputs are rejected
- Specify checkable objects: variables, outputs, check blocks, resources
- Test passes when the specified objects fail as expected
When Users Ask About CI/CD Integration
Recommend:
- Run
terraform testin CI pipeline - Include
terraform fmt -check,terraform validate, andterraform test - Set up cloud credentials as secrets/environment variables
- Use
-verboseflag for detailed CI output - Separate unit tests from integration tests for optimal CI performance:
- Run unit tests (plan mode) on every PR:
terraform test tests/*_unit_test.tftest.hcl - Run integration tests (apply mode) only on merge to main or scheduled:
terraform test tests/*_integration_test.tftest.hcl - Unit tests are fast (seconds) and free; integration tests are slow (minutes) and cost money
- Example: Run unit tests in ~10 seconds for quick feedback, integration tests in ~5 minutes nightly
- Run unit tests (plan mode) on every PR:
Common Errors and Solutions
"Test failed: assertion failed"
Issue: Assertion condition evaluated to false
Solution: Review the error message, check actual vs expected values, verify variable inputs. Use -verbose for detailed output.
"Provider authentication failed"
Issue: Missing credentials for integration tests Solution: Either configure provider credentials (for integration tests) or use mock providers (for unit tests, requires v1.7.0+).
"Cannot reference run block output"
Issue: Trying to reference outputs from a parallel run or invalid run block name
Solution: Ensure run blocks are sequential (not parallel) and use correct syntax: run.<block_name>.<output_name>
"Module source not supported"
Issue: Test references Git or HTTP module source Solution: Terraform test only supports local and registry modules. Clone Git modules locally or use registry sources.
"Tests interfere with each other"
Issue: State conflicts between tests
Solution: Use different modules (automatic separate state), state_key attribute, or mock providers for isolation.
Test Organization Best Practices
File Naming
Organize by test type using clear naming conventions:
tests/
├── defaults_unit_test.tftest.hcl # Unit test (plan mode - fast, no resources)
├── edge_cases_unit_test.tftest.hcl # Unit test (plan mode)
├── validation_unit_test.tftest.hcl # Unit test (plan mode)
├── full_stack_integration_test.tftest.hcl # Integration test (apply mode - creates real resources)
└── multi_region_integration_test.tftest.hcl # Integration test (apply mode)Benefits:
- Clearly distinguishes unit tests (plan mode) from integration tests (apply mode)
- Makes it easy to run tests selectively:
terraform test tests/*_unit_test.tftest.hcl - Self-documenting file names indicate test type and resource implications
Run Block Naming
Use descriptive names that explain the test scenario:
- Good:
run "test_with_3_availability_zones" - Good:
run "test_invalid_cidr_rejected" - Bad:
run "test1" - Bad:
run "test"
Assertion Error Messages
Write clear error messages that help diagnose failures:
- Good:
"Should create exactly 3 subnets across availability zones" - Good:
"VPC CIDR must be within 10.0.0.0/8 range for private networks" - Bad:
"Test failed" - Bad:
"Wrong value"
Test Writing Strategy
Start with Unit Tests (Plan Mode)
- Test default configuration works
- Test variable overrides
- Test conditional logic
- Test resource counts and attributes
- Test outputs are defined correctly
All with command = plan - fast, free, no real resources.
Add Integration Tests (Apply Mode) Selectively
Only for:
- Critical infrastructure paths
- Actual resource behavior validation
- Provider-specific features
- Real cloud service interactions
Use command = apply sparingly - slower, costs money, creates real resources.
Use Mocks for Isolated Unit Testing
When available (Terraform 1.7.0+):
- Mock external data sources
- Mock dependencies between modules
- Test logic without cloud provider calls
- Fastest option for pure logic testing
How to Work with This Repository
No Build System
This is a documentation-only repository:
- No compilation or build commands
- No package manager or dependencies
- No automated tests
- No Docker or containerization
Making Changes
When updating documentation:
- Keep examples accurate - All code examples must use valid Terraform test syntax
- Update version-specific features - Note when features require specific Terraform versions
- Test command accuracy - Ensure all CLI commands are correct
- Maintain consistency - Terminology should be consistent throughout
Version Control
Use Git for all changes:
git status # Check current changes
git add <files> # Stage changes
git commit -m "message" # Commit changes
git push # Push to remoteDocumentation Style Guide
Code Blocks
All Terraform test examples use HCL syntax:
# Correct test structure
run "test_example" {
command = plan
variables {
key = "value"
}
assert {
condition = resource.example.attribute == "expected"
error_message = "Clear, helpful error message"
}
}Terminology Consistency
Use these exact terms consistently:
- Test file (not "test configuration" or "test script")
- Run block (not "test block" or "test case")
- Assert block (not "assertion" or "check")
- Integration test for
command = apply(creates real resources) - Unit test for
command = plan(no real resources) - Mock provider (not "fake provider" or "stub provider")
Command Format
Always use the full command format:
# Correct
terraform test
terraform test tests/defaults.tftest.hcl
terraform test -verbose
terraform test -filter=test_vpc_configuration
# Not abbreviated
tf test # Don't useCLI Commands (Terraform Test)
# Run all tests
terraform test
# Run specific test file
terraform test tests/defaults.tftest.hcl
# Run with verbose output
terraform test -verbose
# Run tests in specific directory
terraform test -test-directory=integration-tests
# Filter tests by name
terraform test -filter=test_vpc_configuration
# Run tests without cleanup (for debugging)
terraform test -no-cleanupNote: These are subcommands of the regular terraform CLI, not a separate tool.
Key Differences from Other Testing Frameworks
Users familiar with other testing frameworks may have incorrect assumptions:
vs. Terratest (Go-based)
- Terraform Test: Native, no additional languages, HCL syntax
- Terratest: Requires Go, programmatic testing, more flexibility
vs. Kitchen-Terraform (Ruby-based)
- Terraform Test: Built-in, no external dependencies
- Kitchen-Terraform: Requires Ruby and Test Kitchen setup
vs. Terraform Compliance (Policy)
- Terraform Test: Tests actual infrastructure behavior and logic
- Terraform Compliance: Policy-as-code, compliance checks only
Terraform Version Requirements
Key version milestones:
- Terraform 1.6.0: Terraform test introduced
- Terraform 1.7.0: Mock providers added
- Terraform 1.9.0:
state_keyandparallelattributes added
Always check user's Terraform version if they request features from newer versions.
Integration with HCP Terraform / Terraform Cloud
Terraform tests work with:
- Local Terraform CLI (most common)
- HCP Terraform / Terraform Cloud (run tests in workspace context)
- CI/CD pipelines (GitHub Actions, GitLab CI, etc.)
Tests access the same state and variables as regular Terraform operations.
Common User Questions
"Should I use Terraform test or Terratest?"
Terraform Test: Start here for most projects
- Built-in, no additional setup
- Perfect for module testing
- Native HCL syntax
Terratest: Consider when:
- Need complex test logic
- Testing across multiple tools (Packer, Docker, etc.)
- Already invested in Go ecosystem
"How do I test without creating real resources?"
Two options:
- Use
command = plan(validates logic without creating resources) - Use mock providers with
command = plan(requires Terraform 1.7.0+)
"Can I test Terraform Cloud/Enterprise features?"
Yes, but with limitations:
- Test runs in context of your workspace
- Remote state access works normally
- Sentinel policies and run triggers are not tested
- Cost estimation is not included in test runs
"How do I test modules in a monorepo?"
Use the module block in run blocks:
run "test_vpc_module" {
module {
source = "./modules/vpc"
}
# ...
}Each module can have its own tests/ directory with test files.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

