Bindings Are Capability References, Not Just Environment Variables
A Worker can deploy cleanly and fail on its first request because one name in env resolved to nothing. The version accepted the configuration, the deployment moved traffic, and the code discovered the gap only when it called a capability that was never attached.
A resource binding is a handle, not a copy. env.ORDERS is not a bucket name or a connection string; it is an object the runtime hands to the Worker, with methods that reach one specific resource. The code sees a capability, while the Terraform address behind it stays outside the application.
The binding name is the contract. Code asks for an exact name, and the version's binding list must contain it. Renaming the binding without changing the code is a breaking change; changing only the target behind the same name is a silent data change.
Provisioning and access are separate acts. Creating a namespace or bucket only makes an object exist. The binding is what grants runtime access to it, and removing the binding leaves the resource intact. Neither act implies the other.
| Binding family | Terraform type | Target field | Runtime shape | Wrong-target symptom |
|---|---|---|---|---|
| KV namespace | kv_namespace | namespace_id | key-value calls such as get and put | a read returns null instead of the sentinel |
| R2 bucket | r2_bucket | bucket_name | object calls such as get, put and head | the object is missing or the bucket errors |
| D1 database | d1 | id | SQL calls such as prepare and batch | the query runs against the wrong schema |
| Queue producer | queue | queue_name | send and sendBatch | messages reach the wrong consumer |
| Durable Object | durable_object_namespace | class_name | a stub or RPC call to one class | the class or namespace is not found |
| Service binding | service | service | fetch or RPC against another Worker | the call reaches the wrong Worker or entrypoint |
| Plain text | plain_text | text | a string value | code treats a string as a capability |
| Secret | secret_text | text | an encrypted string value | rotation becomes a version change |
Queues split the producer from the consumer. The producer binding belongs to the Worker version, while the consumer is a separate cloudflare_queue_consumer resource. Copying a Wrangler consumer block into the binding list creates a producer where a consumer was intended.
Durable Objects bind to code as well as storage. The binding names an exported class, and the class must exist in the deployed code with its migration applied. A binding created before the class is live points at a namespace that does not exist yet.
Service bindings are private calls, not hostnames. They invoke another Worker by name and optional entrypoint, so a missing target is a deploy or first-call failure rather than a DNS lookup. That privacy is useful, and it also hides the dependency from network diagrams.
Variables and secrets are binding types too. A plain variable is a text binding; a secret has the same shape with an encrypted value. Neither is a general bag for every Wrangler field, which is why the next translation step is field by field.
%%{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
OBJ["Terraform resource
creates the target"] -->|"supplies ID or name"| BIND["Version binding
name + type + target"]
CODE["Worker code
env.ORDERS"] -->|"looks up the name"| BIND
BIND --> CAP["Capability handle
methods, not a copy"]
CAP --> STORE["KV, R2 or D1
read and write data"]
CAP --> ASYNC["Queue or Durable Object
send and coordinate"]
CAP --> COMP["Service or string
call or read"]
BIND -->|"name absent"| FAIL["Undefined at runtime
first call throws"]
CAP -->|"target wrong"| WRONG["Valid call, wrong data
no deploy error"]
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 OBJ,CODE,COMP primary;
class BIND,CAP secondary;
class STORE ok;
class ASYNC warn;
class FAIL,WRONG danger;
Missing is louder than wrong. An absent name usually throws on the first property access, while a wrong target returns a valid empty result or writes somewhere else. A smoke test that checks only for a 200 sees neither the second failure nor the first one's cause.
The type decides the proof. A storage binding needs a sentinel read, a queue needs a delivered message, a Durable Object needs a state round trip, a service binding needs a target response, and a string binding needs presence plus whatever the application does with it. Testing every binding the same way produces evidence for none of them.
Translate Wrangler Configuration into the Selected Terraform Schema
Wrangler and Terraform describe the same Worker in different grammars. With Terraform 1.17.1 and provider 5.28.1, the difference is concrete: Wrangler groups settings by product, while Terraform flattens the serving capabilities into one list with a type discriminator. A literal search-and-replace produces a plan that validates and binds the wrong field.
Start from the version, not the Worker. The Worker resource holds identity, the version holds code and bindings, and the deployment holds the traffic pointer. Putting a capability on the identity resource is not a schema option; it is a category error that survives review because the names look plausible.
The bindings list is flat by design. Every element carries a name, a type and a target, and the type decides which target field the provider reads. Wrangler's separate arrays for KV, R2, D1, queues, services and Durable Objects all collapse into that one list.
Copy values, not Wrangler key names. KV expects a namespace ID, R2 expects a bucket name, D1 expects a database ID, and a queue expects a queue name. The Wrangler spelling is a hint, not the schema.
| Wrangler source | Terraform location | Exact field | Note |
|---|---|---|---|
kv_namespaces | version bindings | namespace_id | one element per namespace |
r2_buckets | version bindings | bucket_name | optional jurisdiction |
d1_databases | version bindings | id | the database ID, not its display name |
queues.producers | version bindings | queue_name | producer only |
queues.consumers | cloudflare_queue_consumer | queue_id and script_name | separate resource, not a binding |
services | version bindings | service | optional entrypoint |
durable_objects.bindings | version bindings | class_name | optional script_name for another Worker |
vars | version bindings | text | type plain_text |
secrets | version bindings | text | type secret_text |
main, compatibility date and flags | cloudflare_worker_version | main_module, compatibility_date, compatibility_flags | part of the version contract |
routes | cloudflare_workers_route | pattern and script | one resource per route |
workers_dev | cloudflare_worker | subdomain.enabled | identity-level setting |
Compatibility settings travel with the code. The version carries the compatibility date and flags, and dropping them during a port can change runtime behavior without changing a single binding. Treat them as part of the contract, not as boilerplate to fill in later.
Bindings sit on an immutable version. A meaningful change replaces the version and leaves the previous one available; it does not edit the existing version in place. That is good for rollback and bad for anyone who expects a binding edit to be a quiet in-place patch.
Some fields are build inputs. Bundling rules, local dev settings and build hooks produce the artifact that Terraform uploads. They are not resource attributes, and inventing a binding for them hides which tool owns the build.
Vars do not survive as a map. Each Wrangler variable becomes its own binding element, so the natural Terraform shape is a loop over the map that emits one element per key. Keep the names stable; the map is an input, while the binding list is the contract.
Durable Objects need sequencing. A first apply that both creates the class and binds to it can fail because the migration is applied by a deployment. The documented workaround is a two-step apply, which is a sequencing fact rather than a provider defect.
Queue consumers are a separate resource. The version gets the producer binding; the consumer resource carries the batch, retry and dead-letter settings. This is the translation error most likely to pass a plan and fail in production.
%%{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
W["wrangler.jsonc
source of intent"] -->|"main, compatibility,
flags, assets, migrations"| V["cloudflare_worker_version
immutable snapshot"]
W --> T{"Which field?"}
T -->|"KV, R2, D1, queue producer,
service, Durable Object,
vars, secrets"| BIND["bindings list
one type per element"]
T -->|"queues.consumers"| QC["cloudflare_queue_consumer
separate resource"]
T -->|"routes and custom domains"| RT["route and custom domain
zone-scoped resources"]
T -->|"build, dev, module rules"| GAP["Build-time only
keep in Wrangler"]
BIND --> V
V --> D["cloudflare_workers_deployment
traffic pointer"]
D --> LIVE["Production traffic"]
V -->|"DO class not migrated"| FAIL["First apply or call fails"]
V -->|"compatibility dropped"| BAD["Runtime behavior shifts"]
GAP --> REVIEW["Document the split
one owner per surface"]
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 W,V,D primary;
class T,BIND secondary;
class QC,RT ok;
class GAP,REVIEW warn;
class FAIL,BAD danger;
Watch the optional deploy flag. The version resource can create a 100% deployment when deploy = true, which is convenient for a lab and dangerous in a root that also owns a deployment resource. Two traffic owners can disagree without either plan showing a conflict.
The legacy script resource is a migration path. New work should use the split identity, version and deployment resources; mixing the legacy resource with them for one Worker creates two owners of one binding set.
Reordering the list is noise. The schema treats bindings as an ordered list, so a stable order, for example by name, keeps unrelated edits out of the diff. It does not change the runtime contract.
Check the schema for the pinned release. A provider blog post or an old example can be one major version behind, and the nested field names are where that shows up. Validate against the installed provider schema instead of a copied snippet.
Keep Environment Bindings Explicit and Isolated
The same binding name in dev, stage and prod is a feature; the same target is an incident. Application code should not know which environment it runs in, while every version's target IDs must differ.
Wrangler environments are config overlays; Terraform has no per-Worker equivalent. An environment section in Wrangler becomes a separate Worker name, and each name needs its own version and deployment resources. There is no parent-child inheritance of binding targets across those resources.
Isolation is a stack, not a flag. Separate accounts are the strongest boundary; separate zones, Worker names, resource IDs, API tokens and state files each remove a class of accident. One shared token in a single root defeats the others quietly.
Credentials follow the same boundary. A token that can write production Workers should not be available to a developer laptop or a preview job. Separate tokens per environment and per pipeline, scoped to the account and the needed products, make a misconfigured target fail closed instead of silently writing the wrong environment.
Keep binding names stable; vary the targets. Code reads the same name in every environment, and the version maps it to the dev, stage or prod resource. If the name changes per environment, the application has to branch on configuration and the contract is gone.
Make every target a required input. A variable with a production default is a loaded gun: a missing value binds production without a warning. Required inputs and a plan-time precondition that environment and target agree are cheaper than an incident review.
Do not share a secret across environments. A dev value that also opens production makes the dev credential a production credential. Use separate stores or separate secret names, and separate read permissions.
| Surface | dev | stage | prod | Isolation rule |
|---|---|---|---|---|
| Worker name | orders-dev | orders-stage | orders-prod | name carries the environment; code reads only binding names |
| KV, R2 and D1 | var.kv_id_dev | var.kv_id_stage | var.kv_id_prod | distinct IDs, required with no defaults |
| Queue and consumer | dev queue | stage queue | prod queue | consumer is environment-specific |
| Secret route | dev store or name | stage store or name | prod store or name | no shared value or store |
| API token | dev token | stage token | prod token | one token per root; prod not available locally |
| State | dev state key | stage state key | prod state key | separate state and lock |
State belongs to the boundary. A plan is only meaningful when it compares one environment's configuration with one environment's state. Workspaces can separate state keys, but separate roots or accounts make the boundary visible in the repository and the credentials.
A preview URL is not a fourth environment. A preview version still resolves the bindings recorded in that version. If they point at production data, the preview is a production client with a different hostname.
Drift can hide in the deployment pointer. A version can be correct while the deployment still selects an older one, so the environment record should name the version and deployment under Terraform ownership, not only the target IDs.
One Worker has one uploader. Splitting dev and prod between Wrangler and Terraform can be deliberate, but the boundary must be the whole Worker. Two tools writing bindings for one Worker will overwrite each other's list.
A module must not guess the environment. Passing an environment name and letting the module choose IDs by convention hides the target from the caller. Pass the IDs explicitly and let the module enforce naming and validation.
Trace Secrets Through Provider Inputs and State
A secret is not safe because the plan prints a redacted value. The value passes through a variable, a plan file, state, a version and a deployment, and each artifact has its own exposure. Trace the whole chain before making a write-only claim.
In provider 5.28.1, a Worker secret is a binding. The standalone cloudflare_workers_secret resource from the previous major version is gone; the current path is a secret_text element in the version's binding list. The value arrives through the shared text attribute, which the schema marks sensitive.
Sensitive is not write-only. Terraform redacts a sensitive value in human-readable output, but it still records the value in state and in a saved plan. A write-only argument is a separate feature, and this binding does not expose one.
A plain variable is not shown in the clear. The same text attribute is used for plain variables and secrets, so the provider marks it sensitive either way. Plan redaction therefore says nothing about whether Cloudflare encrypted the value; the binding type does.
A secret change creates a new version. Because the binding is part of an immutable version, rotation replaces the version rather than editing it. The deployment must move to the new version before the new value can serve traffic.
Rotation overlaps two versions. During a gradual deployment, old and new versions can both receive traffic, so both credentials may need to be valid at once. Rotate at the provider, deploy the new version, then revoke the old credential after the old version drains.
Rollback changes meaning after a secret change. A deployment that would return traffic to a version created before the secret changed is normally blocked; the resource exposes a force option for that case. Using it re-enables the old secret path, so treat it as a security decision.
Owning the version is not owning the traffic. If Terraform creates a rotated version but does not own the deployment, the new version may never serve. The plan looks successful while production keeps the old secret.
| Secret route | Where the value lives | Terraform state | Rotation unit | Ownership note |
|---|---|---|---|---|
secret_text binding | the version's binding list | value in state, marked sensitive | new version, then deployment | Terraform is the only writer of the list |
secrets_store_secret binding | Secrets Store, addressed by store and name | only the reference when the value is external | the store secret value | version can stay unchanged |
| Workers Secrets API or Wrangler | Cloudflare's secret store, outside Terraform | absent | new version created by that tool | Terraform must not also manage the name |
The Secrets Store route changes the unit of rotation. A store binding carries a store ID and a secret name rather than the value, so the value can rotate while the Worker version stays the same. That decouples credential rotation from code deployment, which is exactly what a short-lived credential needs.
The store value is still a Terraform value if Terraform writes it. The provider marks the value sensitive, and the API does not return it, but the schema is not a write-only argument. If the value must stay out of state, create it outside Terraform and let Terraform own only the binding reference.
An API read restriction is not a state guarantee. Cloudflare refusing to return a secret proves the read path; it says nothing about what Terraform stored after apply. Check the schema for a write-only attribute and inspect a canary value in state before claiming absence.
Declare out-of-band secrets as external. A value written by Wrangler or the dashboard is not in the configuration, so Terraform cannot rotate it or promise to preserve it. Give that binding name one external owner and verify that a version upload leaves it intact before relying on the split.
State encryption is necessary, not sufficient. Encrypting the backend protects the artifact at rest; it does not remove the value from a saved plan, a CI workspace or a state read by a privileged token. Minimize readers and retention as well.
Terraform cannot check that the code reads the name you wrote. A binding named API_KEY and code reading API_SECRET both validate; the mismatch appears on the first request. Keep binding names in the contract and test them like an API.
| Artifact | Contains the value? | Visible in normal output? | Control |
|---|---|---|---|
| Variable definition | no, only a reference | not applicable | keep the value in a CI secret store |
| Saved plan file | yes | no, unless the file is inspected | encrypt and restrict it; delete after apply |
| Human plan output | no, redacted at render time | redacted as sensitive | do not read redaction as absence in the plan file |
| State file | yes | no, but readable by state access | encrypted backend and least privilege |
| Version binding | yes, encrypted at rest | no read-back | rotate through a new version |
| Deployment | no, it references a version | not applicable | the deployment is the traffic decision |
The defensible claim is narrow. For this release, the value is sensitive in output and present in state; it is not write-only. Any stronger statement needs evidence from the exact provider build and resource.
Detect a Binding Mismatch Before Sending Production Traffic
A plan proves the reference was written; it does not prove the capability works. The gap between those facts is where a binding mismatch lives, and it closes only with a request.
Test four states for every binding. The success path, a missing name, a wrong target and a denied capability each produce a different failure. A successful call alone cannot distinguish a correct target from one that silently points at an empty resource.
Missing is loud; wrong is quiet. An absent name usually throws on first property access, while a wrong namespace or bucket returns a valid empty result. The quiet case needs a sentinel value or a known object, not just a status code.
Denial usually belongs to the control plane. Bindings are pre-authorized capabilities, so a missing token permission or entitlement commonly fails the apply or upload rather than returning a runtime 403. Test the deploy identity separately from the request path.
Build a binding health route. A dedicated path can check presence and perform one cheap read per binding, returning a per-name report without secret values. Run it against the candidate version before shifting production traffic.
Keep the probe free of side effects. A sentinel read, a head request on a known object, a constant query and a service health call are safe. Sending a queue message or writing a row changes state, so reserve those for a disposable environment.
Record the version, not just the status. Evidence should name the version that was tested, the deployment percentage, the binding names and the observed error class. A 200 from an older version says nothing about the candidate.
A candidate at zero percent is not deployed. A version can exist without serving traffic, which is useful for an upload check and useless for runtime proof. Send at least one request to the candidate version, through a preview URL or a small traffic slice, before calling the binding verified.
| Symptom | Likely cause | Safe check | Evidence to record |
|---|---|---|---|
| Undefined property on first call | binding name absent from the version | compare code names with the binding list | version ID, name, error class |
| Call succeeds but data is empty | wrong namespace, bucket or database | read a sentinel written by the test | target ID, sentinel result |
| Object or table not found | target exists but the schema is missing | a constant query or a head on a known key | target name, error class |
| Apply or upload rejected | token permission or product entitlement | confirm with a narrower read-only token | operation, token scope, error |
| New behavior is not live | deployment still selects the old version | read the deployment's version IDs | deployment ID, version IDs |
| Secret rejected after rotation | new version not deployed, or old version still serving | compare the version binding with the deployment split | version ID, rotation time |
Verify a capability binding
Execution status: design-only. The steps use a disposable account and a staging Worker. No account, token or request was used to produce this article, and every identifier below is a placeholder.
Prerequisites. Terraform CLI 1.17.1, Cloudflare provider 5.28.1, a staging Worker with a KV namespace, an R2 bucket and a D1 database, plus permission to create versions and deployments. A read-only token is useful for the denial test.
Setup. Keep four records beside the configuration: a binding contract, an environment map, a secret trace and an evidence log. The contract is the artifact the lab is really testing.
| Record | What it holds |
|---|---|
| Binding contract | Name, type, target resource and expected runtime method for every capability |
| Environment map | dev, stage and prod target for each name, with no default values |
| Secret trace | Where the value lives, which artifact contains it and who can read it |
| Evidence log | Version, deployment, probe result and error class for each test |
- Write the contract before writing HCL. Give every binding a name the code already uses, a type from the pinned schema, and one target per environment.
- Create the resources and a sentinel in each: a KV key, an R2 object and a D1 row with a known value. Keep the sentinel value non-sensitive.
- Create one version with the correct bindings and a health route that checks presence plus one cheap read per name. Return a per-name report, never a secret value.
- Deploy that version to the staging Worker only. Confirm the deployment names the version you tested, not an earlier one.
- Break the name: create a second version with one binding name misspelled, deploy it, and request the health route. Expect a named failure for that capability, not a generic 500.
- Break the target: point the same name at an empty namespace or bucket, deploy, and request the health route. Expect presence to pass and the sentinel read to fail.
- Break the identity: attempt an apply or upload with a token that lacks one required permission. Expect a control-plane denial before any request reaches the Worker.
- Restore the correct binding, deploy, and confirm every name passes and each sentinel matches.
- Rotate a secret through the selected route. On the binding route, confirm a new version and a moved deployment; on the store route, confirm the version is unchanged.
- Tear down the staging Worker, its versions and the sentinel data, then revoke the test token. Confirm no production binding was touched.
Expected observation. The correct version passes every check. The misspelled name fails only that capability. The empty target passes presence but misses the sentinel. The under-scoped token fails before runtime. Rotation replaces the version on the binding route and leaves it unchanged on the store route.
Failure checks. The lab fails if the health route can only return "ok", if the empty-target case is indistinguishable from success, if the tested version is not the deployed version, or if any secret value appears in committed evidence.
Cost and cleanup. Plan-only work is free. A staging Worker with a few sentinel objects and one D1 row stays within ordinary usage; no traffic generation is needed. Destroy the lab root, delete the sentinel data and revoke the token.
Evidence to keep. The binding contract, the environment map, the redacted health report, version and deployment IDs, the three negative-test results and the secret trace. The trace should show where the value is stored without reproducing it.
The contract is the deliverable, not the green apply. A binding table that names each capability, its target per environment and the test that proves it is worth more than a screenshot of a successful deployment. The plan is evidence of intent; the probe is evidence of capability.
Next in the Series
In R2 and KV: Provision Storage Without Turning State into a Data Store, we'll explore Manage buckets, namespaces and storage policy while keeping bulk content and runtime mutation in their proper workflows.