Is there a way to expose the operation type (apply/destroy) to an external data provider

I have an external data script which I’m using to gather environment data not available from the current provider ecosystem. It performs environment error checking intended for applies, which often false-alerts on destroy. Is there a way to pass the Terraform operation type to the external data script so it can better handle environment error checking?

Did you get an answer?

Nope. And the project I asked this question about has been sunset so I’ve stopped researching it. Good luck.

I didn’t see this the first time around, but belatedly:

By default, providers don’t participate in planning a destroy operation at all, but can opt into doing so with a new protocol feature. I think the latest plugin framework does that opt-in automatically and so did detail might not matter, but I’m not 100% sure (since I don’t work on the framework) so I mention it just in case.

Assuming your provider is opted in to participating in destroy planning, you can recognize the destroy case during the planning phase by the prior state being set but the configuration being unset, which represents that this object no longer exists in the desired state.

A similar mechanism exists for the apply phase too: Terraform Core will submit the “planned new state” (the result of the earlier planning step) and it will be unset/null if the plan was to destroy this object.

With that said, providers intentionally have only a limited view of the world where they can only see one resource instance at a time and must plan and apply them in isolation. If the goal is to enforce some sort of guardrail or local policy then I’d instead recommend doing that as an extra automated step between the plan and apply phases, which you might think of as a partially-automated review of the plan.

To do that:

  • terraform plan -out=tfplan to create a plan and save it to disk.
  • terraform show -json tfplan to obtain a JSON description of the plan intended for external integrations.
  • run your own program written in any language that can read JSON to check the result of the previous step to see if it’s acceptable. Fail if not.
  • if not failed, after the plan has been approved by a human reviewer (if necessary) run terraform apply tfplan to apply the plan.

This assumes running the Terraform workflow in automation, but by the time a team is worrying about guardrails and policy enforcement it’s typically already past time to be running Terraform in automation, so that you can be sure that it’s always running consistently regardless of who is making a change, rather than dealing with differences between operators workstations.