In a Terraform `.tftest.hcl` file using a setup helper module, how do state keys decide which `run` blocks can run in parallel and what cleanup destroys first?
answer
- in-memory state, tracked by a key
- the module source as a default identity
- three conditions for running together
- the most recent writer goes first
- dependencies Terraform can actually see
basics
~20 sTerraform test files keep one in-memory state per state key: by default the main configuration and each helper module source. Run blocks sharing a key never run concurrently, and cleanup destroys the most recently updated state first.
solid answer
~50 sEach test file starts with empty in-memory state, one per state key. Runs with no `module` block share the main key, runs with a `module` block share a key per module source, and `state_key` overrides that. Two runs execute concurrently only if both have `parallel = true`, neither references the other's outputs, and their keys differ, so `test { parallel = true }` over runs on the main configuration stays serial. Cleanup works backwards: as of Terraform 1.17, the order follows the run graph, and the state a later run updated goes before the states that run depended on. So a helper re-applied last is destroyed first, and teardown fails if the module still uses it. I keep the setup run first, pass values through `run.setup.<output>` so the dependency is visible, avoid hard-coded shared names, and run in a dedicated account, since leftovers need manual cleanup.
code
hcl · 21 lines# tests/apply.tftest.hcl
provider "aws" {
region = "eu-central-1"
}
run "setup" {
module {
source = "./testing/setup"
}
}
run "creates_flow_logs" {
variables {
log_bucket_arn = run.setup.bucket_arn
}
assert {
condition = aws_flow_log.this.log_destination == run.setup.bucket_arn
error_message = "flow logs do not point at the log bucket"
}
}go deeper
Recall that a test file holds its own temporary state, separate from real state, and that Terraform tries to destroy everything it created when the file ends.
Explain how the default state key comes from the main configuration or the module source, and what state_key changes. Predict which blocks in a given file share a state.
Diagnose why parallel = true changed nothing and why teardown failed. Trace the last writer per key, spot a helper re-applied late, and replace hidden name-based dependencies with run output references.
Decide how much complexity a module's test files may carry. A single setup block first keeps teardown automatic; anything cleverer buys speed with cleanup risk and a bill for whoever owns the test account.
## State inside a test file While `terraform test` executes a `.tftest.hcl` file it keeps the state it needs **in memory, starting empty**, entirely separate from any existing state for the configuration. It may hold several of these internal states per file, each tracked by a **state key**: | `run` block | State key it uses | |---|---| | No `module` block, no `state_key` | The shared key for the main configuration under test | | `module { source = "./testing/setup" }`, no `state_key` | A key derived from that module source, shared by every block loading it | | Any block with `state_key = "primary"` | `primary`, shared with any other block naming it | This is what a **setup helper module** rests on. A `run` block with a `module` block creates prerequisites in its own state, and the module under test reads them through `run.setup.<output>`. The `module` block in a test file accepts only `source` and `version`, and only local and registry sources. Sharing a key means sharing one state: each apply plans that block's configuration against everything in it, so objects a later configuration does not declare are planned for destruction, as in any apply. ## What parallel really requires Run blocks execute sequentially by default. Setting `parallel = true` on a `run` block, or in the file's `test` block, only makes a block **eligible**. Two blocks actually run together only when: 1. Both have `parallel` set to `true`. 2. Neither references the other's outputs. 3. They do not share a state file. The third rule surprises people. Files whose blocks all target the main configuration stay serial however `parallel` is set, because they all share one key. In the source, a block is ordered after an earlier one if either is not parallel or if the two have the same key, regardless of whether they plan or apply. So even a plan-only file needs a distinct `state_key` per block to gain anything. A block with `parallel = false` acts as a synchronisation point: blocks before it finish first, and blocks after it wait. Two flags cap the concurrency, both defaulting to 10: `-run-parallelism` limits `run` blocks within a file and `-parallelism` limits operations within a run. Test files themselves are processed one at a time. **The trap is the dependency Terraform cannot see.** Terraform knows only about references. If the module under test finds the helper's object by a hard-coded name instead of `run.setup.<output>`, the two blocks have no relationship in the graph, and with `parallel = true` the second can start before the first has finished. Separate state keys also start empty, so giving each block its own key means each creates its own copy of everything, and fixed names collide. ## How cleanup orders itself At the end of each file, Terraform attempts to destroy everything it created, state by state. The documented rule is **reverse `run` block order**: the state most recently referenced goes first. In the 1.17 source, each state belongs to the run that most recently updated it, a plan-only run never takes that role, and a state is cleaned up before the states its owning run depended on. Terraform 1.17.0 also made this cleanup ordering deterministic. For the plain pattern, setup first and the module afterwards, this just works. It breaks when the order of the last writes stops matching the real dependency: - A helper **re-applied after** the module under test, to change its input, now owns the most recent write. Its state is destroyed first, while the module's objects still use it. - Parallel blocks related only by a shared name have no ordering in cleanup either. The destroy itself skips refresh, overrides `prevent_destroy`, and uses the configuration and variables of the run that owns the state. ## Diagnosing a failed teardown When a shared network module's apply file leaves objects behind: 1. Read the diagnostics. Terraform says why the destroy failed and lists what was left, stating that it needs to be cleaned up manually. 2. List, per state key, the last `command = apply` block. That gives you the destroy order. 3. Replace hard-coded names between blocks with `run.<name>.<output>` references. 4. Remove the actual leftovers by hand. In stable 1.17 the `skip_cleanup` attribute, a `backend` block in a `run` block and `terraform test cleanup` are available only in experimental builds. Interrupts matter too. One interrupt finishes the current work, skips the remaining blocks and still tidies up; a second stops immediately without cleanup, and a killed process tidies nothing. That is why the documentation recommends a dedicated testing account you can routinely and safely purge.
- Why not give every `run` block in an apply file its own `state_key` so the whole file runs in parallel?Each new key starts with an empty state, so every block creates its own copy of the module rather than building on earlier blocks. Fixed resource names then collide, and costs multiply. Blocks that need earlier objects must reference their outputs, which orders them anyway. It suits independent cases, not a sequence.
- What happens to created resources when a `terraform test` process is interrupted?On one interrupt, Terraform finishes the current work, skips the remaining `run` blocks and still attempts cleanup. On a second, it stops immediately, does not clean up and tries to print what was left behind. A process killed outright tidies nothing, which is why a dedicated, regularly purged test account matters.
- How is `-run-parallelism` different from `-parallelism` on `terraform test`?`-run-parallelism` limits how many `run` blocks execute at once within a file, and `-parallelism` limits plan and apply operations within a single run. Both default to 10. Neither makes a block eligible: that still takes `parallel = true`, no references between the blocks and separate state keys.
A setup helper module is scaffolding: it goes up first and comes down last. Re-applying it late is like putting fresh scaffolding up at the very end, so it is the first thing removed while the building still leans on it.
- Setting parallel = true in the test block makes every run block in the file execute concurrently.
- Each run block gets its own fresh state, so earlier runs' resources are gone by the next block.
- Cleanup always destroys the main configuration first and the helper modules afterwards.
- terraform test reads and writes the configuration's real backend state, so it can overwrite live state.
- A hard-coded shared name is enough for Terraform to order two parallel run blocks.
- The next stable terraform test run automatically retries the cleanup of anything a failed run left behind.
Assumes Terraform 1.17, whose 1.17.0 release made the test framework's cleanup graph ordering deterministic; skip_cleanup and terraform test cleanup stay experimental-only there.