Terraform testing works best as a layered workflow: validate configuration first, inspect the planned changes, test reusable modules with controlled inputs, enforce policy before apply, and reserve live integration tests for changes that genuinely require provider or cloud behavior. This guide provides a reusable checklist for testing Terraform changes before they reach production.
Overview
Infrastructure as Code testing is not a single command or test type. A syntax check can confirm that Terraform can parse a configuration, but it cannot tell you whether a security group is too permissive, a module creates the wrong number of resources, or a database replacement will interrupt an environment. Reliable Terraform testing combines several checks with different costs and purposes.
A practical pipeline usually follows this order:
- Format and validate: catch syntax, type, and basic configuration errors.
- Generate and inspect a plan: identify unexpected creates, updates, destroys, replacements, and drift-related changes.
- Run module tests: verify input handling, resource relationships, defaults, and important plan attributes.
- Run policy-as-code checks: reject configurations that violate security, reliability, naming, tagging, or cost rules.
- Run integration tests when needed: apply selected infrastructure in an isolated environment and verify real provider behavior.
Keep these layers separate in your CI/CD workflow. Fast checks should run on every pull request, while slower or more expensive tests can run for changes that affect particular modules, providers, or environments. The goal is not to maximize the number of tests. It is to catch meaningful failures before an irreversible or costly apply.
Checklist by scenario
For every Terraform pull request
- Run the formatter and fail the check if files are not formatted consistently.
- Initialize providers and modules using the repository’s lock file and expected upgrade policy.
- Run configuration validation with the same Terraform or OpenTofu family used by the deployment workflow.
- Generate a plan using safe, non-production credentials and an appropriate remote-state workflow.
- Review resource additions, deletions, replacements, changes to access controls, and changes to data storage.
- Save the plan artifact only when your team has defined how it is protected and who can consume it.
A plan check should be more deliberate than “the command returned zero.” Review whether the change matches the pull request description. A replacement of a production database, load balancer, or encryption key deserves explicit approval even if Terraform considers the plan valid.
For reusable modules
Terraform module testing should cover the module’s contract rather than every implementation detail. Define representative inputs, including the smallest supported configuration, a normal production-like configuration, and important optional features. Then check outputs and planned resource attributes that users depend on.
- Test required variables, defaults, validation rules, and invalid combinations.
- Check that expected resources are present and unexpected resources are absent.
- Assert critical attributes such as encryption settings, network placement, protocols, ports, retention behavior, and identity bindings.
- Verify outputs have stable names, types, and meanings.
- Test conditional resources, count or for_each behavior, and empty-list or empty-map inputs.
- Include at least one negative test for a configuration the module must reject.
Terraform’s native test framework can express configuration-driven tests in files commonly named with a .tftest.hcl suffix. Use run blocks to execute plans or applies and assertions to check known conditions. The exact syntax and supported features can vary between Terraform and OpenTofu releases, so verify examples against the version pinned by your repository.
For fast unit-style tests without cloud resources
Use provider mocking or controlled test inputs when you want to evaluate module logic without creating real infrastructure. Mocking is useful for checking resource selection, conditional expressions, defaults, and output composition. It is not proof that an API accepts every attribute or that two cloud services work together correctly.
Where the selected Terraform or OpenTofu version supports it, a test can define a mock provider and assert values from the resulting plan. Keep these tests focused. For example, a module test might confirm that a private subnet is selected when a private-network option is enabled, while an integration test verifies that the resulting service can actually reach its dependency.
For provider, network, or identity changes
Use an integration test when behavior depends on a real provider API, eventual consistency, permissions, generated identifiers, networking, or service-side defaults. Run the test in a temporary account, project, subscription, or isolated environment where possible.
- Use dedicated state and uniquely identifiable resource names.
- Limit credentials to the permissions required by the test.
- Set timeouts and cleanup behavior explicitly.
- Capture logs and the failed plan or apply output for diagnosis.
- Always define what happens if cleanup fails.
Integration tests should verify outcomes, not merely that an apply completed. Check connectivity, identity permissions, health status, encryption configuration, or recovery behavior when those are part of the module’s purpose.
For security, reliability, and cost controls
Add policy-as-code checks before the apply stage. Policies can inspect a plan or configuration for conditions such as public exposure, missing encryption, unapproved regions, absent ownership tags, oversized resources, or unrestricted identity permissions. Tools and integrations vary; teams commonly evaluate approaches based on OPA and Conftest, Sentinel, or platform-specific policy engines.
Keep policy failures understandable. A failed rule should identify the resource, the violated condition, and the remediation path. Separate hard controls from warnings so engineers know which findings block deployment and which require review.
Test-selection matrix
| Change | Minimum checks | Consider adding |
|---|---|---|
| Variable, local, or output logic | Format, validate, module test | Negative and boundary tests |
| Resource arguments or dependencies | Plan assertions, policy checks | Provider integration test |
| IAM, firewall, or network rules | Plan review, policy-as-code | Connectivity and permission tests |
| Provider or module upgrade | Validation, plan, module tests | Full integration test in isolation |
| State, import, or migration change | Plan review and backup verification | Restore or migration rehearsal |
What to double-check
Version alignment: Pin or otherwise control the Terraform or OpenTofu version, provider versions, and module dependencies used in CI. A test that passes locally but uses a different provider lock file is not a reliable gate.
Plan inputs: Use representative variable files and environment settings. A plan created with missing optional inputs may conceal behavior that appears in staging or production.
Unknown values: Some values are unknown until apply. Avoid brittle assertions that require generated IDs or provider-computed values to be known during planning. Assert stable intent instead, such as whether encryption is enabled or whether a resource is created.
Secrets and state: Do not place credentials in test files, command output, or committed plan artifacts. Treat state and plans as sensitive because they may contain configuration details or values derived from secrets.
Destructive actions: Make replacements and destroys visible in CI. Require an explicit approval path for environments where a test could affect shared or persistent resources.
Drift: A clean test result does not mean the real environment matches configuration. Include a separate drift review process; see the Terraform drift detection and remediation workflow for a related operational checklist.
Common mistakes
- Testing only syntax: Validation catches configuration errors but does not evaluate the safety of a successful plan.
- Testing only after apply: Live tests are valuable, but they are slower, more expensive, and potentially destructive. Keep fast plan and policy checks earlier in the pipeline.
- Asserting implementation details: Tests that depend on incidental resource names or ordering become noisy during harmless refactoring. Assert the module contract and operational intent.
- Using mocks as a substitute for integration tests: Mocks cannot reproduce every provider validation rule, permission boundary, or service interaction.
- Ignoring negative paths: Invalid CIDR ranges, unsupported combinations, missing tags, and overly broad access should have deliberate failure tests.
- Allowing CI to hide failures: Avoid commands that swallow exit codes or continue after a failed security or plan check without clearly marking the result.
- Sharing state between tests: Shared state creates order dependence and makes failures difficult to reproduce. Isolate test state wherever practical.
When to revisit
Review this Terraform testing checklist before seasonal planning cycles, before introducing a new module, and whenever your workflow or tools change. Revisit it after upgrading Terraform or OpenTofu, changing provider versions, adopting a new policy engine, moving CI platforms, or changing remote-state and credential practices.
Use a short maintenance routine:
- Confirm that the documented test commands still run with the repository’s pinned versions.
- Review failed tests from recent pull requests and add coverage for recurring defects.
- Compare policy rules with current security, reliability, ownership, and cost expectations.
- Run at least one integration test for critical provider paths and verify cleanup.
- Remove tests that no longer describe supported behavior and document intentional exceptions.
Start small: add formatting, validation, a plan review, and one meaningful module test to the pull-request workflow. Then introduce policy checks and targeted integration tests as the infrastructure grows. That layered approach gives engineers fast feedback while preserving a clear safety net for changes that can affect production.