Terraform Native Test Framework Prompt
Write `.tftest.hcl` tests using Terraform's built-in test framework — `run` blocks, `command = plan` vs `apply`, assertions, mocks, and providers — to validate modules in CI without third-party tooling.
- Target user
- Module authors adopting the native `terraform test` command
- Difficulty
- Intermediate
- Tools
- Claude, ChatGPT
The prompt
You are a module maintainer who has converted a suite of Terratest Go tests over to Terraform's native `.tftest.hcl` framework and shipped it in CI.
I will provide:
- The module under test (variables, resources, outputs)
- What behaviors matter (defaults, validation, conditional resources, computed outputs)
- Whether we can do real `apply` against a sandbox or must stay plan-only
Your job:
1. **Plan vs apply tests** — explain when a `run` block should use `command = plan` (fast, no resources, asserts on planned values and validation) vs `command = apply` (real resources, asserts on actual outputs, requires teardown). Default to plan-only unless an output is only known after apply.
2. **Test file layout** — propose `tests/*.tftest.hcl`, naming, and how each `run` block composes (later runs reuse state from earlier `apply` runs in the same file).
3. **Assertions** — write `assert { condition = ... error_message = ... }` blocks for: default values, conditional resource creation (`length(...) == 0`), output shape, and `variable validation` rejection (using `expect_failures`).
4. **Inputs per run** — show passing different `variables { }` per `run` block to cover multiple scenarios in one file.
5. **Mocking providers** — use `mock_provider` and override `mock_resource` / `override_data` so tests run with zero cloud credentials and no real API calls. Show overriding a `data` source to return fixed values.
6. **Provider config for apply tests** — when real apply is needed, scope to a cheap, isolated sandbox; ensure teardown always runs even on assertion failure.
7. **CI wiring** — the `terraform test` invocation, how to fail the build on any failed assertion, caching `.terraform`, and keeping runtime under a couple of minutes.
8. **Migration note** — map common Terratest patterns to native equivalents and flag what native testing still can't do (so they know when to keep Go tests).
Output as: (a) one plan-only `.tftest.hcl`, (b) one mocked-provider test, (c) a validation/`expect_failures` test, (d) the CI step, (e) guidance on plan-only vs apply coverage.
Bias toward: plan-only + mocked providers for the common case, real apply only where an output demands it, and an error_message on every assertion.