Terraform Test
Terraform's built-in testing framework validates that configuration updates don't introduce breaking changes. Tests run against temporary resources, protecting existing infrastructure and state files.
Reference Files
references/MOCK_PROVIDERS.md— Mock provider syntax, common defaults, when to use mocks (Terraform 1.7.0+ only — skip if the user's version is below 1.7)references/CI_CD.md— GitHub Actions and GitLab CI pipeline examplesreferences/EXAMPLES.md— Complete example test suite (unit, integration, and mock tests for a VPC module)
Read the relevant reference file when the user asks about mocking, CI/CD integration, or wants a full example.
Core Concepts
- Test file (
.tftest.hcl/.tftest.json): Containsrunblocks that validate your configuration - Run block: A single test scenario with optional variables, providers, and assertions
- Assert block: Conditions that must be true for the test to pass
- Mock provider: Simulates provider behavior without real infrastructure (Terraform 1.7.0+)
- Test modes:
apply(default, creates real resources) orplan(validates logic only)
File Structure
Use *_unit_test.tftest.hcl for plan-mode tests and *_integration_test.tftest.hcl for apply-mode tests so they can be filtered separately in CI.
Test File Structure
Run Block
Common Test Patterns
Validate outputs
Conditional resources
Resource counts
Tags
Data sources
Validation rules
Sequential tests with dependencies
Plan options (refresh-only, targeted)
Parallel modules
State key sharing
Cleanup ordering (S3 objects before bucket)
Multiple aliased providers
Complex conditions
Cleanup
Resources are destroyed in reverse run block order after test completion. This matters for dependencies (e.g., S3 objects before bucket). Use terraform test -no-cleanup to skip cleanup for debugging.
Running Tests
Best Practices
- Naming:
*_unit_test.tftest.hclfor plan mode,*_integration_test.tftest.hclfor apply mode - Test naming: Use descriptive run block names that explain the scenario being tested
- Default to plan: Use
command = planunless you need to test real resource behavior - Use mocks for external dependencies — faster and no credentials needed (see
references/MOCK_PROVIDERS.md) - Error messages: Make them specific enough to diagnose failures without running the test again
- Negative tests: Use
expect_failuresto verify validation rules reject bad inputs - Variable coverage: Test different variable combinations to validate all code paths — test variables have the highest precedence and override all other sources
- Module sources: Test files only support local paths and registry modules — not git or HTTP URLs
- Parallel execution: Use
parallel = truefor independent tests with different state files - Cleanup: Integration tests destroy resources in reverse run block order automatically; use
-no-cleanupfor debugging - CI/CD: Run unit tests on every PR, integration tests on merge (see
references/CI_CD.md)


