An API Operation Is Not Always a Managed Resource
Ownership is a promise to keep something in a state, not a receipt for an API call. A managed resource has an address, a schema, a create/read/update/delete lifecycle and an entry in state. An operation has a request, a result and perhaps an audit event. It has no ongoing desired state to converge, so Terraform has nothing to compare against on the next plan.
Ask whether the object survives the call. A VPC, a queue, a DNS record and a database persist, drift and can be repaired. A cache purge, a Lambda invocation, a certificate reissue and a backup trigger finish when the API returns. Treating the second group as resources produces state entries that can never be refreshed honestly.
Ask what destroy would mean. Deleting a queue has a clear meaning and a real consequence. Deleting the record of an invalidation means nothing. If you cannot write a truthful destroy operation, you probably do not own a resource; you own a history of having called one.
Ask who can repair drift. Terraform can only reconcile what it can read back. An operation that leaves no readable object cannot be imported, planned against or repaired. A resource whose read function returns the last request from state is a log with an address, not a model of infrastructure.
Provider-native operations come in two shapes. Some providers model an operation as a resource, such as a CloudFront invalidation with an identity, a readable status and a meaningful delete. Others expose an action, which has no state at all. Choose the shape the provider actually implements instead of wrapping the API yourself; the provider already made the lifecycle decision.
The anti-pattern has a recognizable shape. A resource named after a verb, a create that calls an endpoint once, a read that echoes state, and a delete that does nothing. It plans cleanly and passes review, then teaches the team that state is an append-only log of side effects. The test is still address, read-back and a truthful destroy. Figure 1 separates the decision from the mechanism.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["Need to change
something through an API"] --> B{"Does an object
persist afterwards?"}
B -->|"yes"| C["Managed resource
address, CRUD, state"]
B -->|"no"| D{"Does the provider
define an action?"}
D -->|"yes"| E["action block
CLI invoke or trigger"]
D -->|"no"| F{"Must it run inside
this apply?"}
F -->|"yes"| G["terraform_data plus
a provisioner"]
F -->|"no"| H["External job or
platform API"]
C --> I["Drift is detectable
destroy is meaningful"]
E --> J["No state entry
result in run output"]
G --> K["Tainted on failure
replaced next apply"]
H --> L["Terraform waits only
if you make it wait"]
B -->|"wrapper has no
truthful destroy"| X["State becomes a log,
not a model"]
F -->|"no stable trigger"| Y["Runs on every apply
or never runs"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class A primary;
class B,D,F secondary;
class C,I,E,J ok;
class G,K,H,L warn;
class X,Y danger;
Figure 2 makes the boundary physical. The top band is the only layer Terraform can reconcile; the middle band it can invoke but not remember; the bottom band it hands off entirely. Most bad designs move an operation upward until it looks like ownership.
Use Terraform Data for Explicit Local Dependency Semantics
terraform_data is a state container, not a provider substitute. The built-in resource is always available through Terraform's built-in provider, so it needs no download or configuration. It implements the standard lifecycle, but the only thing it manages is the value you hand it. It never reads or writes a real API.
The input argument stores a value. When the value changes, the instance updates in place. That update does not replace the resource, and it does not rerun a creation-time provisioner. Teams that expect a new script hash to trigger a rerun are usually surprised by a clean plan.
The triggers_replace argument is a replacement trigger. Any change replaces the instance, which also makes it the supported way to turn a plain local value into something the lifecycle block can consume. It is a trigger, not a scheduler.
The store block covers ephemeral input. A write-only value can be captured during apply and exposed through a sensitive output, which is useful when a credential must survive one resource's lifetime but must not appear in the plan. The version argument freezes the stored output until you deliberately rotate it.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["terraform_data instance"] --> B{"What changed
since last apply?"}
B -->|"input"| C["In-place update
value replaced in state"]
B -->|"triggers_replace"| D["Replacement planned"]
B -->|"nothing"| E["No-op plan"]
D --> F["Old instance removed
new instance created"]
F --> G["Creation provisioner runs"]
G -->|"exit 0"| H["New value recorded
next plan is a no-op"]
G -->|"exit non-zero"| I["Apply fails
container is tainted"]
I --> J["Next apply replaces
and runs the script again"]
C --> K["No side effect repeated
provisioner stays idle"]
E --> H
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class A primary;
class B,F secondary;
class C,E,H,K ok;
class G warn;
class D,I,J danger;
The intended uses are narrow and useful. Anchor a provisioner when no real resource is the logical parent; adapt a plain value for a replacement trigger; hold ephemeral material for a later consumer. All three are wiring problems. None of them is a reason to model a database, a bucket or a DNS zone inside Terraform Data.
The anti-pattern is a timestamp in the trigger. A value that changes on every evaluation replaces the resource on every apply, so the script always runs and the plan never converges. That is a cron job wearing a state file. Use an explicit revision, a content hash or an operator-set generation number instead.
A rerun is safe only when the trigger is stable. Feed the container a digest of the script and the target, not the current time. Then a second apply with unchanged inputs is a no-op, and a changed digest produces exactly one replacement. If the plan always offers a replacement, the trigger is doing the opposite of its job.
Provider Actions Do Not Record Resource State
An action is a provider-defined verb, not an object. You declare it with a type and a label, configure it through the action's config block, and may add count, for_each or an alternate provider. A special caller symbol exposes the resource instance that triggered it, which lets one action block serve many instances without hand-built references.
The CLI invocation is deliberately narrow. Pointing plan or apply at an action runs only that action and excludes the rest of the configuration. That makes it a targeted day-two tool rather than a second, quieter apply. It also requires a workspace; Stacks do not support local invocation.
The lifecycle trigger is where most teams get surprised. An action_trigger inside a lifecycle block accepts six events, an optional condition and one or more actions. The action still writes nothing to resource state, so its success is evidence about the call, not about the resource.
Failure policy changes the meaning of the run. The default halt stops the apply and reports an error without tainting. Continue logs a warning and proceeds. Taint stops the apply and marks the resource for replacement, which is a severe response to a failed notification or cache purge.
The action anti-pattern is a hook that quietly owns state. An action that creates the object a later resource expects to find leaves no address for the next plan to reconcile. The resource either duplicates the object or reports drift that no refresh can explain. Use an action for verbs, and a resource for nouns; taint belongs to neither when the verb is optional.
The table below compares the escape hatches by what Terraform remembers and what happens when they fail. The distinction that matters is not syntax; it is which system owns the outcome. The details follow the v1.17 documentation, current for Terraform 1.17.1.
| Mechanism | State entry | When it runs | Failure semantics | Use when |
|---|---|---|---|---|
| Managed resource | Yes: address, attributes, drift | Create, update or destroy as planned | Apply fails; next plan shows drift or partial state | The object persists and must be reconciled |
| Action, CLI invoked | No | Only when -invoke targets it | Command fails; no resource is tainted | A targeted day-two operation |
| Action trigger | No | Before or after create, update, destroy | Halt by default, or continue or taint | The operation must follow a resource event |
| Creation provisioner | Only the parent resource | After create, first apply only | Fail taints the parent and fails the apply | No provider-native or image-based option exists |
| Destroy provisioner | Only the parent resource | Before destroy | Error; reruns on the next apply | Last-chance cleanup with stable configuration |
| Terraform Data plus provisioner | Yes, for the container only | On create or replacement | Fail taints the container; next apply replaces | A script needs an explicit replacement trigger |
| External job | No | Whatever schedules it | Pipeline status; Terraform is unaware | Work is long-running or crosses systems |
Figure 3 shows the asymmetry. The resource lane has a state file and a destroy step. The action lane has an invocation and a result, and removal of the block leaves no trace. A successful action is not proof that the resource converged.
Provisioners Need a Last-Resort Justification
Terraform's own documentation calls provisioners a last resort. The reason is not taste. Terraform cannot predictably model what a script does, so it cannot plan the result, detect drift in it or undo a partial run. Most provisioners also need direct network access and credentials, which widens the blast radius of the runner.
Build the configuration earlier in the lifecycle. A custom image bakes packages and files into an artifact that can be versioned, scanned and rolled back. Cloud-init or user data runs at first boot without inbound access from the runner. Configuration management converges a fleet on its own schedule. Each option moves the work into a system that can observe it.
Creation-time failure taints by default. A failed provisioner fails the apply and marks the resource for replacement, because a half-configured server cannot be trusted. Setting the failure mode to continue keeps the resource and hides the defect. Neither behaviour is a retry, and neither proves the service is ready.
Destroy-time behaviour has sharper edges. The provisioner runs before the object is removed; a failure returns an error and reruns on the next apply. It is skipped when the resource is tainted, and skipped entirely when create-before-destroy is active. Removing the resource block also removes its destroy provisioner, so removal needs the two-step count-zero sequence.
Sensitive and ephemeral values are not a complete answer. Terraform suppresses sensitive values in logs, and ephemeral values are excluded from plan, state and log output, but a remote script still lands on the target filesystem and command output is still streamed. Quiet mode suppresses only the command echo, not what the command prints. SSH host keys are also unverified by default.
The provisioner anti-pattern is work that belongs earlier. Installing packages that should be in the image, joining a cluster that configuration management should own, or copying a secret that a secret manager should inject all trade reproducibility for convenience. A destroy-time provisioner used as a backup is worse: it runs only if the block survives, and it is skipped for tainted resources.
Figure 4 traces the two failure paths. The left path decides whether a bad creation keeps or replaces the object. The right path decides whether cleanup ever runs. Both are lifecycle questions, not scripting questions.
Make Side Effects, Credentials and Retries Reviewable
A safe escape hatch has five recorded parts. A trigger says why the operation runs now. An operation key says which logical call it is. A precondition and a postcondition say what must be true before and after. Evidence says what actually happened. Miss one and the next engineer is guessing.
Prefer a server-side idempotency key over a local marker. If the target API accepts a key, put the stable operation key in it so a repeated call collapses onto the first. A marker kept only in state can be lost in a state rebuild or bypassed by an out-of-band run, which makes the "already done" claim untrustworthy.
Secrets must travel beside the command, not inside it. Environment variables and ephemeral inputs keep a credential out of process listings and plan files. A command line is visible to other local users and is often captured by audit tooling. Never interpolate a secret into a shell string, and never assume quiet mode redacts the program's own output.
Make failure loud and local. Both actions and provisioners default to stopping the apply, which is the right default for work that prepares a service. Continue belongs only to genuinely optional work with a separate alert. Add an independent check so a zero exit code is not the only proof of success.
Prove rerun safety with a plan, not an argument. After a successful run, apply again with unchanged inputs; a stable trigger should produce no changes. Change the input and expect an in-place update with no repeated side effect. Change the trigger and expect exactly one replacement. A plan that always replaces means the trigger is unstable.
Prove failure visibility with a forced failure. Point the script at a missing endpoint in a sandbox, confirm the apply fails, and confirm the resource or container is marked as expected. Then confirm the alert fires and the evidence record names the trigger, key, target and exit code. Cleanup that cannot fail visibly is not a control.
Choose a post-deployment operation
Scenario. A container image is deployed by a managed resource. After each successful rollout the team must purge a CDN path and run a smoke test. A contractor proposes a local-exec provisioner on the service resource.
- Classify the work. Neither the purge nor the smoke test persists as an object, so neither is a resource. Reject the wrapper before discussing syntax.
- Check the provider first. If the CDN provider exposes a purge action, declare it and trigger it after update. Use a condition so it fires only when the image digest changed.
- Name the logical operation. Use a key such as the zone plus the image digest. Send it as the API idempotency key if one exists; otherwise record it in the run message and the evidence record.
- Choose the fallback honestly. If no action exists, use a Terraform Data container whose replacement trigger is the image digest, and call a wrapper that checks purge status before calling the API.
- Set the failure policy. Halt on failure and page the service owner. Do not continue: a stale cache after a rollout is a correctness incident, not a warning.
- Rerun the plan unchanged. Expect no changes and no invocation. A replacement here means the trigger includes a changing value such as time or a random id.
- Force one failure in the sandbox. Expect a failed apply, a visible alert, and an evidence record naming the key, target, trigger and exit code.
Evidence packet. Keep the operation key, trigger value, target, start and end time, exit code, run id and the operator or pipeline identity in one record. Link it from the change ticket so the next reviewer can answer "did this run, and did it run once?"
Pass condition. An unchanged apply is a no-op, a changed trigger runs exactly once, and a failed run stops the apply and produces an alert plus the evidence packet. If any of the three is missing, the hatch is still a manual step with better branding.