Expose a Capability Rather Than Arbitrary Shell Execution
A ticket is not a request contract. A ticket asks for "a payments sandbox in eu-west-1, a /24 network, Postgres, and access for the data team." The old runbook ends with terraform apply -auto-approve in a repository the requester cannot read. The new service shows six fields and a button. That is the platform boundary.
Think of a restaurant. A menu is a capability contract: named dishes, known ingredients, prices, and a kitchen that decides how the work is done. Letting diners into the kitchen is not self-service. A platform API is a menu; a shell endpoint with a terraform_vars map is the kitchen pass.
The boundary has four parts.
Approved capabilities. A capability is a named, owned unit of infrastructure, such as an AWS environment, a GCP project baseline, or a Cloudflare zone onboarding. The catalog is an allowlist, not a search box over every module in the organisation. Each entry names the owner, provider, allowed environments, cost class, and support contact. A request selects a capability; it cannot select an arbitrary module source.
Validated inputs. Validation happens before a run exists. Types, enums, patterns, numeric bounds, CIDR ranges from an allocated pool, and naming rules are checked. Dangerous values are derived, not accepted: the account comes from the environment, the subnet from the pool, the role from the capability. A bad request returns field errors and creates nothing. Every free-form string that reaches a module can become a name, a filter, a command argument, or part of a policy document; the module decides how much power that carries.
A versioned module catalog. Each capability resolves to an immutable reference: a semantic version plus a commit SHA, never a branch. The entry records the wrapper root, provider constraint, Terraform version, and contract version. Old requests keep resolving to the version they were reviewed against. Upgrades are catalog changes with a diff, a deprecation window, and a migration note, not a side effect of a Tuesday terraform init.
Bounded permissions. Two identities meet here. The requester's identity authorises the request. The runner's identity can plan and apply only the named workspaces, and cannot create IAM roles, change its own trust policy, read every state file, or pass arbitrary roles. The caller never receives the runner's credential. If the API accepts a role_arn from the request body, the boundary is decorative.
Every escape hatch restores the shell
A free-form field is a shell with a form around it. A free-form variables object, a module-source field, a run-command parameter, caller-supplied target addresses, or a custom JSON escape hatch each hand arbitrary execution back to the requester. -target narrows a plan to part of a graph; it is a debugging tool, not a self-service control.
Figure 1 traces a request from capability to queued run, including the three places it should stop.
%%{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["Requester picks
a capability"] --> B{"In the approved
catalog?"}
B -->|"no"| B1["404, no run"]
B -->|"yes"| C["Validate inputs
against schema"]
C -->|"invalid"| C1["422, no run"]
C -->|"valid"| D["Resolve immutable
module ref"]
D --> E{"Policy, quota and
environment pass?"}
E -->|"no"| E1["403 or 409"]
E -->|"yes"| F["Mint bounded
run identity"]
F --> G["Queue plan with
request id"]
G --> H["202 with request
and run ids"]
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,C,D,G primary;
class B,E,F secondary;
class H ok;
class B1,C1,E1 danger;
Figure 2 draws the boundary as layers, because most failures are a layer leaking into the one above it.
Treat the Plan and Run as Reviewable Artifacts
A platform API does not have to implement Terraform. It has to make a run identifiable, reviewable, and recoverable. HCP Terraform's Runs API is a useful reference even if you run everything yourself: it separates a configuration version, a run, a plan, an apply, and a set of permitted actions. The behaviour below was checked against that documentation on 5 November 2026.
A run is a sequence of small, recorded steps. Select a configuration version, create a run, poll it, approve the plan, then apply. The create call carries a workspace, a configuration version, optional run-specific variables, a message, and lifecycle flags; the response returns a run id and a status.
Do not export your vendor's state machine. HCP Terraform documents sixteen run statuses; expose all of them and the requester has to learn a vocabulary you do not control. Map them to eight contract states and keep the raw status in evidence (Runs API).
| Vendor status | Contract state |
|---|---|
pending, fetching | accepted |
plan_queued, planning | planning |
planned, policy_checking, policy_checked, planned_and_saved | awaiting_approval |
confirmed, apply_queued, applying | applying |
applied, planned_and_finished | succeeded |
errored | failed |
canceled, force_canceled | cancelled |
| no vendor status | timed_out |
Permissions are booleans on the run, not a reading of its status. The actions block reports whether the run is confirmable, cancelable, discardable, or force-cancelable; those flags are the contract for what a client may do next. Do not infer permission from a status string.
Approval is a digest, not a button
POST /runs/:run_id/actions/apply queues an apply; calling it is not approving the plan. Approval is a named person's decision about a specific plan digest. Record the approver, digest, run id, commit, and expiry in one object. If auto-apply is enabled there is no approval artifact at all: fine for a sandbox, not for production. Keep approver and runner identities separate, and make the apply endpoint unreachable to the requester.
Three operations are easy to confuse. A normal cancel interrupts the Terraform process and asks it to stop safely. A force-cancel terminates it and unlocks the workspace, requires admin access, and needs a cool-off after a normal cancel. Discard skips a paused run and does not interrupt running work.
Cancelled means work stopped, not world restored
A create that reached the cloud may still exist, and a destroy that ran is not undone. Neither cancel nor force-cancel is a rollback. Mixing the three produces a support queue where nobody can tell whether a change happened.
Audit correlation is the design output. One request record should join the requester, capability, catalog version, configuration version, commit, lock-file digest, run id, plan id, apply id, policy results, approver, terminal status, and transition timestamps. HCP Terraform exposes created-by, run-events, and relationships to the plan, apply, and configuration version, plus its status timestamps. Use them instead of rebuilding the story later from log timestamps.
Figure 3 shows the lifecycle a requester should see, including the approval boundary and the fact that cancellation does not rewind completed API calls.
%%{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'}}}%%
sequenceDiagram
autonumber
participant U as Requester
participant P as Platform API
participant R as Run service
participant W as Worker
participant C as Cloud API
U->>P: POST /v1/requests with Idempotency-Key
P->>P: authorise, validate, resolve catalog
P->>R: create run with request id and pinned source
R-->>P: run id, queued
P-->>U: 202 with request and run ids
R->>W: plan
W->>C: refresh and read
W-->>R: plan, digest, policy results
R-->>P: awaiting approval
P-->>U: plan summary and digest
U->>P: approve this digest
P->>R: apply this run
R->>W: apply saved plan
W->>C: create and update
W-->>R: applied or partial
R-->>P: terminal status and evidence
P-->>U: completion record
Note over U,C: Cancel stops work.
It does not undo completed API calls.
A retry is the quiet failure. A requester whose browser times out may POST again, and a naive service creates a second run against the same workspace. An idempotency key maps repeats to one request; reusing it with a different body should return 409. Put the key in the run message so an operator can find the run without a database join.
Use Multiple Providers Without Claiming Cross-Cloud Equivalence
A "cloud-neutral" module that accepts a subnet, a security group, and a region looks tidy and lies in four places. The concepts do not line up, and the differences are not naming.
The table maps common intent to each provider's actual object. Versions were checked on 5 November 2026: AWS 6.72.0, azurerm 5.13.0, google 8.10.0, and Cloudflare 5.28.1. Treat it as a starting point for schema reading, not a specification.
| Concept | AWS | Azure | Google Cloud | Cloudflare |
|---|---|---|---|---|
| Network container | VPC, regional | VNet, regional, in a resource group | VPC network, global | No customer-defined VPC |
| Subnet | Zonal, separate resource | Child of the VNet | Regional, separate resource | Not applicable |
| Packet filter | Security group on an ENI, NACL on a subnet | NSG on a subnet or NIC | Firewall rule in the VPC, with priority and targets | WAF rules at the HTTP edge |
| Workload identity | IAM role and STS session | Entra ID object and role assignment | IAM member and service account | API token with account and zone roles |
| Tag or label | Tags, case-sensitive keys | Tags, case-insensitive names | Labels, lowercase and restricted | Metadata and comments |
| Destroy scope | Object by object | Resource group can cascade | Project can cascade | Zone deletion is broad |
Three differences deserve more than a cell.
Scope is a different axis. An AWS VPC is regional; a GCP VPC network is global while subnets are regional; an Azure VNet is regional and belongs to a resource group that is itself a lifecycle boundary; Cloudflare has no equivalent customer-defined VPC. A variable named region means a different thing in each module, and on Cloudflare it may mean nothing.
Policy attachment is a different object. AWS attaches an IAM policy to a role; Azure assigns a role definition at a scope; GCP binds a member to a role on a resource; Cloudflare grants account or zone roles to a token or member. A generic policy_arn input is an AWS shape leaking into every other provider. Name the intent, such as read_only_observability, and let each module resolve it.
Deletion is a lifecycle decision. Deleting an Azure resource group can remove everything inside it. Deleting a GCP project can remove all project-scoped resources. Deleting a Cloudflare zone removes DNS and edge configuration. A "delete environment" button must know which of these it calls.
The honest design is a shared request contract, not a shared resource model. Define capability-level inputs once: owner, environment class, data classification, cost center, region preference, and time-to-live. Then implement one module per provider per capability, each with its own state, credentials, and conformance tests. The tests assert the contract, not resource parity: expected outputs exist, ownership tags are present, destroy removes what the module created, policy checks pass. They do not assert that four clouds produce the same graph, because they cannot.
Cloudflare makes the point sharply. It is an edge network and security platform, not a replacement for a VPC. A cloudflare_ruleset WAF rule and an AWS security group both "filter traffic", but one inspects HTTP requests at the edge and the other controls packets at an elastic network interface. Mapping them in a comparison table is fine; mapping them in a module interface is how a security review fails.
Choose a Provider, an Action or an External Job
Ownership is the deciding question. Once the capability is defined, the implementation choice narrows to who owns the lifecycle of the thing: Terraform with a resource, a provider action for a one-shot call, or a job runner outside Terraform.
| Question | Provider resource | Provider action | External job |
|---|---|---|---|
| What it owns | one object with a state address | one imperative operation | a delivery Terraform should not supervise |
| Terraform does | create, read, update, delete, import, destroy | invokes it; no state entry is created | hands off after apply: pipeline step, queue message, or API call |
| Drift and undo | refresh, compare, plan a correction | no stored result, no automatic undo | retries, progress, logs and rollback belong to the runner |
| Choose it when | durable object, CRUD API, a second apply reconciles drift | one-shot operation with no desired state | deployment, migration, long batch, approval chain, artifact promotion |
| Watch out for | schema changes become a public contract | an unaudited mutation unless you record it | local-exec and remote-exec sit outside the graph; external is a plan-time read that can leak output into state |
Actions cannot modify resource state. They can be invoked from the CLI or triggered from a resource's lifecycle block through action_trigger, with events such as before_create, after_create, and after_update plus an on_failure rule. As of the Plugin Framework v1.18.x documentation checked on 5 November 2026, actions are one-way calls and future work is planned (Actions).
The decision questions are short:
- Does the object need a durable identity Terraform can refresh, import, and destroy? Use a resource.
- Is it a one-shot operation with no desired state? Use an action if the provider has one, otherwise an external job.
- Does it deliver an application artifact or depend on a build pipeline? Use an external job.
- Does it need retries, progress, logs, or a queue? Use an external job and correlate its id back to the request.
- Would failure need to block a resource's creation? Use
action_triggerwith expliciton_failure, and still record the outcome outside Terraform.
An action is an unaudited mutation
A one-shot call that matters must leave evidence. Record its invocation, result, and correlation id in the request record even though it never appears in terraform state list; no plan will show that it happened.
Know the Cost of Owning a Custom Provider
The demo is convincing: one Go file, one resource, terraform apply creates the object. The cost arrives after the demo, and it is not the cost of writing HTTP calls. A provider is a state-machine adapter. Terraform asks it to plan, apply, read, import, upgrade, validate, and destroy, and keeps asking for years while the API changes underneath.
The Plugin Framework is the recommended starting point for new providers and supports protocol versions 5 and 6 (Plugin Framework). A serious resource surface includes a schema, create, read, update, delete, import, plan modifiers, validators, documentation, examples, and acceptance tests. Each attribute has a type, a required or optional or computed flag, a default, and a replacement behaviour. That schema is a public API: renaming an attribute or changing its type breaks every configuration and state file that used it.
State upgrades are where "we'll fix it later" becomes a support incident. Terraform stores a schema version with each object. When the stored shape changes, the provider must ship an upgrader from each prior version, tested against real old state. Without one, the next plan can fail to decode the object, or silently read zero values and propose a destructive replacement. The state may be years old and written by a provider version you no longer run.
Acceptance tests are the other recurring cost. The framework's tests run real Terraform configurations against a real or recorded API, covering create, read, update, import, and destroy (Acceptance Tests). They need credentials in CI, cleanup that survives failures, tolerance for eventual consistency, and a strategy for rate limits. A suite that only mocks the client proves the Go code compiles, not that Terraform can own the object.
The demo ends where the support rota begins
Release engineering is the part the demo never shows. Checksums and signing, registry publishing, protocol compatibility, dependency updates, security advisories, and a support rota are ongoing work. The provider is now part of your platform's public interface: every Terraform upgrade is a compatibility test, and every upstream API change is a potential state migration.
Figure 4 contrasts the demo with the owned lifecycle, and shows the failure path when a schema changes without an upgrader.
None of this argues against custom providers. It argues against underestimating them. A custom provider is justified when the API is a system of record, several teams need it, the semantics fit CRUD, the vendor has no usable provider, and you can staff compatibility work. Otherwise the cheaper options are a reviewed module plus an external job, an upstream contribution, or a provider action for a genuinely one-shot operation.
Implementation details, including schema design, plan modification, and state-upgrade code, belong in the provider deep dive. This part fixes the decision and the budget.
Design a Small Internal Infrastructure Service
A small service can expose the whole boundary without becoming a platform product. Six contracts are enough to design, review, and test it.
Identity. Authenticate with a workload identity, not a shared token. Authorise on the capability and the target scope (environment, account, project, zone). Keep three identities distinct: requester, approver, runner. Short-lived credentials, no long-lived keys in the request path, and no path by which a request can name a different role.
Inputs. Publish an OpenAPI or JSON Schema contract next to the capability card. Validate types, enums, bounds, patterns, and cross-field rules before creating a run. Derive account, network, role, and naming values on the server. Reject unknown fields. Never accept a secret value in the body; accept a reference to a secret path and resolve it under the runner's identity.
Reviewed source. The catalog entry names an immutable module reference and the wrapper commit that was reviewed. A change to either goes through a pull request, diff, approval, and a catalog version bump. Branch references, floating tags, and "latest" are not reviewable. The request record stores the exact reference that ran, so a replay is possible after the catalog moves.
Artifact provenance. Store the configuration version, commit, lock-file digest, plan digest, run id, module version, policy results, approver, and terminal status. With saved plans, the digest identifies the artifact that was approved. If the platform re-plans at apply time, store the comparison result. A plan file contains variables and state, so protect it like state and retain it for days, not months.
Completion. Define terminal states before writing the UI. succeeded should mean the apply completed and the service passed its readiness check, not merely that Terraform exited zero. Use signed webhooks for speed and polling as the fallback, make both idempotent, and expire requests that never finish. "Still applying" after the timeout is an alert, not a spinner.
Recovery. Retries are safe before an apply and dangerous after one. A failed plan can be re-queued; a failed apply needs reconciliation. Cancel stops work and may leave partial objects; force-cancel terminates and unlocks but does not restore. Compensation is a new, reviewed run that removes or replaces what the first created, never an automatic destroy. Tag every object with the request id so an orphan scan can find what state lost. Route unrecoverable requests to a dead-letter queue with the evidence attached.
The lab turns those six contracts into a one-page design and a request-to-run acceptance checklist.
The wrapper enforces the contract again at the Terraform boundary. A direct run must not bypass validation the API already performed. This panel shows the pinned wrapper and the commands that exercise it; the card below turns the rest into a reviewable design.
Design a platform capability
Status: design-only. Nothing here was executed against a cloud account. The versions are pinned for the design: Terraform CLI 1.17.1, hashicorp/aws 6.72.0, Plugin Framework v1.18.x, and the HCP Terraform Runs API as documented on 5 November 2026.
Prerequisites. Terraform CLI 1.17.1, a text editor, Git, and one module you can pin by commit. An HCP Terraform organisation is optional; without one, replace the run API calls with a local script and keep the same state machine.
Setup. Create seven files in one directory:
labs/p36/
├── capability.md # name, owner, scope, TTL
├── request.schema.json # accepted inputs and bounds
├── catalog.yaml # pinned ref, commit, versions
├── wrapper/main.tf # the boundary, enforced again
├── states.md # request state to run status
├── failures.md # failure mode, evidence, pager
└── evidence.md # what a reviewer keeps
- Write the capability card. Name the capability, owner, provider and account scope, allowed environments, promised outputs, cost class, and maximum lifetime. Add one sentence on what it will not do.
- Write the request contract. Require a capability, an environment class, an owner, a region, a TTL, and a cost center as JSON Schema; restrict the enum, bound the TTL, and reject unknown properties.
- Write the catalog entry. Pin the module to a commit, not a branch, and pin the provider and Terraform versions.
- Write the wrapper root. The panel above validates at the Terraform boundary too, so a direct run cannot bypass the contract. Derive the account and network; do not accept them from the requester.
- Map the run API. Write the create, status poll, approval, cancel, and discard calls. Put the request id in the run message. Mark which statuses are terminal and which are waiting.
- Write the state machine. Map each request state — accepted, planning, awaiting approval, applying, succeeded, failed, cancelled, timed out — to a run status and one permitted action. A state with no action is a dead end; one with two needs a rule.
- Write the failure table. Cover validation failure, policy rejection, plan error, partial apply, cancel during apply, timeout, duplicate submission with the same key, and duplicate with a different body. For each: requester view, evidence record, and who is paged.
- Write the acceptance checklist. It should answer: what proves the run finished, what proves the object is usable, what proves the approval matched this plan, what happens if the callback is lost, what happens if apply is interrupted, and how an orphan is found.
Worked values. The sandbox request and the matching catalog entry:
{
"capability": "aws-environment",
"environment_class": "sandbox",
"owner": "payments-team",
"region": "eu-west-1",
"ttl_hours": 72,
"cost_center": "cc-1042"
}
capability: aws-environment
contract_version: 1.4.0
module_ref: 9f2c1ab
provider: hashicorp/aws 6.72.0
terraform: 1.17.1
wrapper: platform/env-request@4b81d0c
owner: platform-team
Expected observation. A one-page contract where every request has one capability, one immutable source, one bounded identity, one approval, one evidence record, and one recovery path. It fails review if any field can name a module, a role, a shell command, or a target address.
Failure checks. The design is unfinished if the requester can reach the apply endpoint, the runner can change its own trust policy, the catalog accepts a branch, "succeeded" means only that Terraform exited zero, or a retry after a partial apply starts again without reconciliation.
Cost dimensions. Zero if you stop at the design. If executed, the sandbox objects and HCP Terraform run minutes are the only costs; set a short TTL and destroy at the end.
Cleanup. Delete labs/p36/, or keep it as a reviewed design with placeholders. If you created a real environment, run the reviewed destroy path and confirm the state list is empty.
Evidence to keep. The capability card, JSON Schema, pinned catalog entry, wrapper HCL, state machine, failure table, and acceptance checklist. Sanitize account identifiers, workspace ids, and state or plan content.