Execute Scripts During Planning to Enable a Dry-Run Mode
Community note
[!TIP] Hi there, OpenTofu community! The OpenTofu team prioritizes issues based on upvotes. Please make sure to upvote this issue and describe how it affects you in detail in the comments to show your support.
OpenTofu Version
OpenTofu v1.11.5
on linux_amd64The problem in your OpenTofu project
Scripts are part of real OpenTofu configurations (local-exec, terraform_data + provisioners, external). Today there is no safe way to test such a script in the environment where it will actually run until the apply is already underway.
Most applies don't run on a laptop. They run on CI build agents, runners, or automation platforms, and each has its own:
- credentials and identity (which account/role the process is actually running as)
- network reach (VPC endpoints, private API servers, egress rules)
- installed tooling (
aws,kubectl,jq, specific versions) - environment variables and working directory
A script that works on an engineer's machine can fail on the agent because of any of these. A provisioner only ever runs at apply, so the first time the script is exercised in the real environment is in the middle of a real apply. By then:
- other resources in the same run may already have been created, changed, or destroyed
- the script itself may have made some of its changes before failing
- the resource is left tainted in state
- fixing it means another PR, another review, another approval, and another real apply. That apply is again the first test of the fix.
The plan step, which is supposed to be where problems show up safely, cannot catch any of this, because nothing about the script runs at plan time. Even when the script has a read-only --dry-run mode, there's no way to have OpenTofu run it during plan, in the apply environment, and show the result in the logs.
Real example: an EKS cluster teardown that failed at apply, repeatedly
Our pipeline:
tofu plan -outruns in a preview job, and a human reviews the output.- A separate job, behind a manual approval, runs
tofu apply <planfile>on a CI runner.
Before a cluster's security groups can be destroyed, a cleanup script has to run from a terraform_data provisioner. It pauses GitOps reconciliation for the cluster, deletes its Ingresses, and deletes any load balancers left over. Every plan was clean. Here's what happened at apply, against a production cluster:
| Attempt | What failed at apply | Could plan have caught it? |
|---|---|---|
| 1 | The script ran as the runner's base identity. The AWS provider's assume_role applies to the provider, not to a provisioner's environment. So aws eks describe-cluster looked in the wrong account and failed with ResourceNotFoundException for a cluster that was ACTIVE. |
Yes, if any part of the script could run at plan. |
| 2 | After the credential fix, the script got further: it built kube contexts and annotated the live GitOps cluster secret (a real change in prod). Then it failed because the controller it restarts was a Deployment on that cluster, not the StatefulSet the script assumed. The apply failed with the prod change already made, and the resource tainted in state. |
Yes. A read-only discovery pass would have hit the same lookup. |
| (latent) | A second script (an orphan-volume sweep that runs after the cluster is destroyed) had the same wrong-account problem. It would not have errored. It would have looked in the wrong account, found nothing, exited 0, and quietly left orphaned volumes behind. We only caught it by manual code audit. | Yes, and a plan-time dry run showing "0 volumes found" would have made it obvious. |
Each row was a full cycle of fix → PR → review → merge → approval → real apply against production, with the apply as the only integration test.
To break the loop we ended up changing the script to hardcode the --dry-run mode (details below) and applying it to test. That found all 10 load balancers the script would delete, and it confirmed the cross-account credentials worked from the runner. That's exactly the information we needed at plan time, before approving anything.
Attempted Solutions
1. Switch the provisioner command on tofu.applying
resource "terraform_data" "probe" {
provisioner "local-exec" {
command = "./cleanup.sh ${tofu.applying ? "" : "--dry-run"}"
}
}- Provisioners never run at plan, so there's no plan-phase run to switch.
- Inside a provisioner
tofu.applyingis alwaystrue, so the--dry-runbranch can never run. - Referencing it suppresses the script's output:
(output suppressed due to ephemeral value in config) - It can't be used in
triggers_replace:Error: Ephemeral value used in non-ephemeral context
We understand this is meant for write-only arguments and provider config. It just can't help here.
2. data "external" for a plan-time dry run
Data sources do run at plan, so this is the closest thing available. We evaluated it but didn't adopt it, because it doesn't give a usable dry run:
- The program must print a flat JSON object of strings. The script's normal output (what it found, what it would do, why it failed) isn't shown, so a failed dry run is hard to diagnose from the CI log.
- With
tofu apply <planfile>nothing is shown again at apply, so the apply job's log has no record of the preflight. - It runs on every plan and refresh, not just when the paired action is about to run.
- The dry run and the real run are two unrelated blocks, so nothing guarantees they get the same arguments or environment. That undermines the point of testing one to validate the other.
3. What we actually do: a dry-run flag and a throwaway apply
resource "terraform_data" "cleanup" {
# the flag MUST be in the trigger, or the real run never fires after the dry run
triggers_replace = [var.cluster_name, var.dry_run ? "--dry-run" : ""]
provisioner "local-exec" {
command = "./cleanup.sh --cluster ${var.cluster_name} ${var.dry_run ? "--dry-run" : ""}"
}
}Set dry_run = true → review → approve → apply (read the log) → set dry_run = false → review → approve → apply again.
- It works, and it's the only way we've found to test the script on the real runner before it changes anything.
- It costs two applies and two approvals, and the "test" is itself a state-mutating apply (
Resources: 1 added, 0 changed, 1 destroyed). - Forgetting to put the flag in
triggers_replaceis a silent failure: the dry-run apply creates the resource, the real apply sees no change, and the destructive step never runs. We only got this right because an automated reviewer flagged it. - The reviewer approving the real apply still never sees the dry-run result in that plan.
Proposal
I'd like a supported way to exercise a script at plan time, in the same execution environment the apply will use, and have its output in the logs. That way environment problems (credentials, network, tooling, assumptions about the target) fail the plan instead of breaking the apply partway through.
I don't have a strong opinion on the mechanism, but something like this would work:
resource "terraform_data" "cleanup" {
triggers_replace = [var.cluster_name]
provisioner "local-exec" {
run_during_plan = true # new flag: also run this provisioner during plan
# Adding the ability to use the `tofu.applying` ephemeral in the provisioner block to be able to run a ternary switch
command = tofu.applying ? "./cleanup.sh --cluster ${var.cluster_name}" : "./cleanup.sh --cluster ${var.cluster_name} --dry-run"
}
}Workarounds and Alternatives
- Throwaway dry-run apply + flag in
triggers_replace(Attempted Solution 3). The only way we've found to test on the real runner. It costs two applies and two approvals, the "test" mutates state, and it fails silently if you forget the trigger. data "external"(Attempted Solution 2). Runs at plan, but hides the script's output, forces a JSON protocol, runs on every plan, and doesn't tie the preflight to the real invocation.- Run the script by hand with
--dry-runbefore approving. This tests the engineer's environment, not the runner's. It's exactly how attempt 1 got through: the script worked with the engineer's credentials and failed with the runner's. - Replicate the runner locally (same image, same role). This is possible in principle, but in practice it's another environment to keep in sync. It also doesn't cover the network position or the injected credentials the runner has at apply time.
With any of the proposals above, the two production failures in the table would have shown up as a failed plan in the preview job, before anyone approved an apply and before anything in production changed.
References
I didn't find an existing issue asking for this, but these are related:
- #2614 — Improving the Reliability of Applies. Same core pain (a clean plan doesn't mean a clean apply, and each failed apply costs another approval cycle). This issue is one concrete cause of that: scripts that can only be exercised at apply. Unlike many of the provider-side causes discussed there, core could address this one directly.
- #3428 — Hooks for pre/post tofu local executions. Also about scripts at specific phases, but focused on when standalone hooks run, not on exercising the apply-time script during plan in the apply environment.
- #3309 — Support
actionblocks. Actions using provider configuration would remove one failure class above (attempt 1: script not inheriting the provider's assumed role), but they still execute at apply, so the "first real test is the apply" problem remains. - #3927 — local-exec output suppressed even with
-show-sensitive. Related to requirement 3: suppressing all output makes a failed script hard to diagnose.
Source: opentofu/opentofu