Back to Terraform

Workers Delivery: Build Artifacts, Versions and Deployments

November 6, 2026 Wasil Zafar 22 min read

Separate Worker identity, immutable application artifacts and traffic deployment decisions

Table of Contents

  1. Separate Worker Identity, Version Creation and Traffic Deployment
  2. Build Once Before Planning the Upload
  3. Choose Routes, Custom Domains and Preview Exposure Explicitly
  4. Assign Terraform and Wrangler Non-Overlapping Responsibilities
  5. Promote and Verify a Version Without Losing the Previous One

Separate Worker Identity, Version Creation and Traffic Deployment

The release was version five. The edge was serving version six.

It had been doing so since a secret rotation two days earlier. Rotating a secret with Wrangler creates a new version and deploys it at 100% in the same step, so the rotation replaced the release without a Terraform plan. The deployment resource still existed, still pointed at version five, and still read back cleanly.

Three objects answer three different questions. A Worker is who the code belongs to, a version is what bytes and settings were uploaded, and a deployment is which of those versions currently receives traffic. Collapsing them is what makes a release feel like a single boolean.

Identity is the cloudflare_worker resource. It carries the account, the name, the workers.dev subdomain settings, observability, tags and tail consumers. It carries no code and no traffic. The read-only fields describe what happened rather than what you want: creation time, update time, and a deployment time that stays null until something is actually serving.

The name is the join key. Versions address the Worker by name or ID; routes and deployments address it by script name. Terraform treats a name change as an in-place update, which is exactly why a rename deserves a migration plan: every route, service binding and deployment record that still names the old script is now pointing at a Worker that no longer answers to it.

A version is an immutable snapshot. It holds the modules, the entry module, the compatibility date and flags, the bindings, static assets, limits and placement. Uploading the same source twice produces two versions; uploading byte-identical output produces two versions with the same content hashes. Cloudflare assigns the version number and ID, and neither is something you choose.

The deploy flag is the coupling you are removing. Left unset, a version is created and receives no traffic. Set to true, the same apply also creates a deployment at 100%, which is the old single-step behavior wearing a new resource name. If promotion is a separate decision, leave it unset and own the deployment explicitly.

A deployment is a pointer, not a setting. It names the script, uses the percentage strategy, and lists versions whose percentages total 100. A normal release lists one version at 100; a gradual release lists two. The resource is create-only in practice: changing the version list replaces the deployment object, and the previous deployment remains in Cloudflare's history rather than being edited in place.

The legacy resource is the coupling in one object. Provider 5.28.1 recommends the Worker, version and deployment resources instead of cloudflare_workers_script, which bundles identity, code and the live deploy into a single address. That bundle is convenient until a comment-only change redeploys production, and then it is the reason nobody can say which part of the apply moved traffic.

Separate Worker Identity, Version Creation and Traffic Deployment
%%{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
    CLIENT["Client request"] --> SURFACE["Route, custom domain
or workers.dev hostname"] SURFACE --> DEP["cloudflare_workers_deployment
90 percent version 5
10 percent version 6"] DEP --> V5["Version 5
reviewed artifact"] DEP --> V6["Version 6
candidate artifact"] ID["cloudflare_worker
identity, name, subdomain"] --> V5 ID --> V6 V4["Version 4
previous release"] RB["New deployment
100 percent version 4"] -.->|"rollback target"| V4 RB -.->|"replaces the split"| DEP SEC["Secret rotation
run outside Terraform"] -.->|"creates a version
and deploys it at 100 percent"| DEP 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 CLIENT,ID,V5 primary; class SURFACE,V6 secondary; class DEP,RB ok; class SEC danger; class V4 warn;
Worker identity, versions and deployments sit at account scope while traffic surfaces sit at zone scope The account scope holds the Worker identity, the immutable version history and the deployment that points at one or two versions. The zone scope holds the route pattern, the custom domain and the workers.dev hostname that clients actually reach. A version URL is a fourth, account-level path that can reach an uploaded version without any deployment pointing at it. Code at account scope, reachability at zone scope A promotion moves the deployment pointer. It does not upload code or touch DNS. Account scope Worker identity and immutable versions cloudflare_worker name, account, subdomain no code, no traffic version 4 previous release version 5 live at 90 percent version 6 candidate at 10 percent deployment 90 percent version 5 10 percent version 6 create-only pointer Zone scope Where clients actually arrive route pattern in one zone, proxied DNS required custom domain exact hostname, DNS and certificate created workers.dev public, Browser Integrity Check always on version URL reaches a version with no deployment at all A version can be reachable without being deployed. That is how preview exposure escapes the traffic model.

Account scope holds code; zone scope holds reachability. A version is uploaded at the account; a route or custom domain is attached at a zone. The deployment sits between them, so a code promotion does not touch DNS and a hostname change does not need a new version.

Read the plan as three separate decisions. A code change should replace the version; a traffic change should replace only the deployment; a hostname change should touch only the route or custom domain. A plan that moves two of those at once is telling you the objects are still coupled somewhere in your configuration.

Build Once Before Planning the Upload

The artifact is a build output, not a source tree. Terraform uploads module bytes, so something has to turn the repository into those bytes before the plan runs. wrangler deploy --dry-run --outdir dist runs the bundler without contacting Cloudflare, and the output directory is the shape the version resource expects.

The bundler makes decisions that change the artifact. It resolves imports, applies aliases and defines, and rewrites the entry point. A different lockfile, bundler version or build-time constant produces different bytes even when the source is untouched.

The bundle is only half of the version. Compatibility date, compatibility flags, bindings, limits and asset configuration are part of the snapshot. Two identical bundles with different flags are different versions with different runtime behavior, so a flag change is a release even when no code changed.

The provider hashes the artifact at plan time. Each module exposes a computed SHA-256, and a changed hash forces replacement of the version resource. That is the diff that makes a rebuild visible: byte-identical output leaves the plan empty, while a changed dependency or a new build timestamp proposes a new version.

The hash is computed at plan; the bytes are read at apply. The provider reads content_file during create. If CI rebuilds between plan and apply, the uploaded version is not the artifact the plan reviewed, so freeze the directory and treat any rebuild in that window as a failed release.

Build once, promote the same bytes. Install with the lockfile, pin Wrangler in the project, and keep the Node version fixed between build and apply, so one commit produces one digest. Staging and production should then differ in bindings and percentages, not in compiled code. Environment-specific defines are the exception: if production needs different bytes, it needs a different version, and the review should say so.

Static assets travel with the version. The asset directory is read at apply and summarized by a manifest hash, so an asset change is a version change too. Header and redirect rules ship as modules, and the base path must match across versions in a split deployment; changing it requires a 100% deploy first.

Worker artifact promotion
%%{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
    SRC["Source, lockfile,
pinned Wrangler"] --> BUILD["Bundler dry run
output written to dist"] BUILD --> ART["Artifact
modules, assets, compatibility"] ART --> HASH["content_sha256
computed during plan"] HASH --> PLAN["terraform plan
version replacement"] PLAN --> FREEZE{"Artifact frozen
until apply?"} FREEZE -->|"yes"| UP["cloudflare_worker_version
uploaded, no traffic"] FREEZE -->|"no"| BAD["Apply reads new bytes
under the reviewed digest"] UP --> DEP["cloudflare_workers_deployment
promotion"] BAD --> DRIFT["Live version does not
match the reviewed artifact"] DEP --> LIVE["Production hostname"] LIVE --> CHECK["Version metadata
and error rate"] CHECK -->|"healthy"| FULL["100 percent to the new version"] CHECK -->|"unhealthy"| OLD["Previous version back at 100 percent"] 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 SRC,PLAN primary; class BUILD,ART,UP secondary; class DEP,LIVE,FULL ok; class BAD,DRIFT danger; class FREEZE,CHECK,OLD warn;

Choose Routes, Custom Domains and Preview Exposure Explicitly

A route attaches a pattern inside one zone. It needs an active zone, a Worker and a proxied DNS record for the hostname. The pattern matches the whole URL, the wildcard is the only operator, and the most specific pattern wins when several could match.

Route patterns are string matches, not subdomain matches. The pattern *example.com/* also matches myexample.com, because the wildcard matches any characters. Use separate apex and subdomain routes when you mean both, and remember that the path is case-sensitive.

A custom domain makes the Worker the origin. Cloudflare creates the DNS record and an advanced certificate for the hostname, so there is no record to write and no certificate to request. The hostname must match exactly: apex and www are two domains, wildcards are not supported, and an existing CNAME blocks the attachment.

Custom domains and routes have different blast radius. A route sits in front of an existing origin and can chain to it; a custom domain replaces the origin for every path on that hostname. A route can run before a custom domain and call it with the incoming request. A route cannot be the target of a same-zone fetch, while a custom domain can.

The two surfaces need different token scopes. Routes are a zone capability and need Workers Routes edit on that zone. Custom domains are managed through the account's Workers Scripts permission, because Cloudflare creates the record and certificate on your behalf. A token with only zone rights will plan a route and fail a custom domain.

Deleting a custom domain does not delete its certificate. The hostname stops routing, but the advanced certificate remains in the zone until someone removes it. That leftover is invisible in Terraform after the destroy, and it is exactly the kind of inventory drift an audit finds six months later.

workers.dev is a convenience surface, not production. Every Worker gets a route on the account subdomain, and Cloudflare treats that subdomain as a free website. Browser Integrity Check always runs there and cannot be disabled, so automated clients with default library user agents receive error 1010 before the Worker executes, and that request never appears in your logs.

Version URLs are public when they exist. They are enabled by default only when no explicit setting exists and workers.dev is enabled, but disabling workers.dev does not disable them. A Worker with workers.dev off can still answer on a version URL with the same bindings as production. They also have no logs, and Workers that implement a Durable Object do not get one at all, so they are a way to hand a reviewer a build, not a staging environment. Access can protect them, one Worker at a time or account-wide; if the decision is "public", write it down.

Test the hostname you actually ship. A test against workers.dev exercises different WAF, cache and Browser Integrity Check behavior than the custom domain. The release check belongs on the production hostname, with the version URL used only to confirm that the uploaded artifact starts.

Assign Terraform and Wrangler Non-Overlapping Responsibilities

Two tools can share a Worker only when they own different fields. The rule is not "Terraform for infrastructure, Wrangler for code", because code is infrastructure here. The rule is that every remote field and every operation has exactly one authoritative writer.

Terraform owns the durable graph. Identity, version, deployment, route, custom domain and cron trigger are addresses in state. Wrangler owns the build: dry-run bundling, local development, type generation and read-only inspection. That split is stable because the build produces a file and Terraform produces remote objects.

The table is the contract. If a row has two owners, the second apply is the incident, and it will usually arrive through a command that looks local.

SurfaceTerraform addressWrangler command or fieldCollision symptom
Identity and namecloudflare_workername in the build configurationA rename creates or claims a second script
Code and compatibilitycloudflare_worker_versiondeploy, versions uploadA version exists that the plan never saw
Traffic splitcloudflare_workers_deploymentversions deploy, secret putA 100% deploy replaces a canary
SecretsSecrets Store binding, or no Terraform fieldsecret put, versions secret putA new version appears with no plan
Routescloudflare_workers_routeroutes in the build configurationA deploy reclaims or drops a pattern
Custom domainscloudflare_workers_custom_domainroutes with custom_domainTwo owners of one hostname
workers.dev and previewscloudflare_worker.subdomainworkers_dev, preview_urlsA toggle flips on the next deploy
Cron triggerscloudflare_workers_cron_triggertriggers in the build configurationSchedules are replaced wholesale

The dangerous command is the one that deploys as a side effect. wrangler secret put creates a version and deploys it at 100%; there is no separate promotion step and no Terraform plan. A rotation run during a canary ends the canary, and the next person to look at Terraform sees a release that no longer exists.

Use the version-scoped secret command, or keep secrets out of the version. wrangler versions secret put uploads a version without deploying it. The cleaner split is a Secrets Store binding, where Terraform writes the binding name and the value rotates behind it without creating a version at all.

Remove the overlapping keys, not just the commands. A build configuration that still declares routes, workers_dev or triggers is a loaded gun: the next person who runs a full deploy will apply them, even if today's pipeline does not. Keep the build inputs and delete the deployment inputs.

Terraform's state is not a traffic monitor. It records the deployment it created, not the deployment that is active. A newer deployment from another tool leaves the resource readable and the plan empty, which is why ownership has to be enforced by credentials and process as well as configuration.

Credential scope is the enforcement. Give the Terraform token Workers Scripts edit and the zone route permission. Give the build job no deploy credential at all, only the ability to produce an artifact. A pipeline that cannot call the deploy API cannot accidentally become a second owner.

Two writers to one deployment field compared with one writer per field On the left, Terraform and a Wrangler secret rotation both write the same Worker. The last write wins, the deployment record in state still points at the older version, and the next plan is empty even though traffic moved. On the right, the build job produces an artifact only, Terraform owns identity, version, deployment and routing, and the secret value is rotated behind a binding that does not create a version. One field, one writer The tool that can create a version can also change traffic. Ownership has to cover both. Before: two writers Terraform apply version and deployment secret rotation creates and deploys one Worker last write wins State still points at the older version. After: one owner per field build job artifact only, no token Terraform identity, version, traffic secret value behind a binding remote fields code and compatibility deployment percentages routes and hostnames worker settings Each row has one writer. Failure path: a secret rotation during a canary The new version goes to 100 percent, the canary disappears, and Terraform reports no change because its deployment still exists.

The plan shape is the test. A code change should show a version replacement and a deployment replacement. A traffic-only change should show the deployment alone. A hostname change should show the route or custom domain alone. When a single-intent pull request produces a third resource in the plan, an overlap has survived the review.

Promote and Verify a Version Without Losing the Previous One

Promotion should change exactly one resource. The version is uploaded, reviewed and left with no deployment. Promotion replaces the deployment and points it at that version. If the new version resource also changes in the promotion plan, the split is not real yet.

A split deployment is two versions. The percentages must total 100, and the platform's gradual deployment is a two-version split rather than an N-way canary. A third version is not a safer canary; it is a shape the deployment model does not offer.

Requests are routed independently. Consecutive requests from one user can land on different versions, so a page reload and its asset fetches can disagree about the API shape. Version affinity pins a user for the duration of the rollout, and a service binding can still cross versions unless a version override pins the downstream Worker.

Keep the previous version addressable. In provider 5.28.1, destroying a version resource does not delete the version in Cloudflare, but it does remove the ID from state. Keep the previous version resource for one release, or publish its ID as an output, so a rollback has something concrete to reference at 2 a.m.

Rollback is a new deployment. It sends 100% of traffic to the selected version, replacing a split with a single version. It does not roll back bindings, storage or data shape, and Cloudflare blocks a rollback when a secret changed between the two versions unless the deployment declares force.

The 100-version window is the real retention limit. Gradual deployment and rollback only reach the last 100 uploaded versions. A pipeline that uploads on every commit will push last week's good version out of range, so upload on release candidates and keep the tag history deliberate.

Verify the version, not the status code. A 200 from the production hostname does not say which version answered. Read the version metadata binding, the version ID in a response header, or the version field in Logpush, and compare it with the version the deployment claims to serve.

Lab

Review a Worker release

Execution status: design-only. The steps use a disposable account and were not run against a live zone to produce this article. Identifiers are written as tokens, not as real IDs.

Prerequisites. Terraform CLI 1.17.1, Cloudflare provider 5.28.1, Wrangler installed in the project, one Worker you can afford to break, and a health endpoint that returns a known body.

Records to keep. The lab is mostly a paper exercise; the table is the artifact a reviewer actually needs.

RecordWhat it holds
artifact.mdCommit, lockfile digest, artifact digest, Wrangler version
versions.mdVersion number, version ID, tag, compatibility date
release.mdDeployment ID, version IDs, percentages, previous deployment
evidence.mdHostname, expected version, observed version, error rate, timestamp
  1. Build once with a dry run into a clean directory. Record the digest of every uploaded module and the total artifact digest before planning.
  2. Plan the version change. Confirm the plan replaces the version resource and leaves the deployment untouched. If the deployment moves too, stop and fix the configuration split.
  3. Apply the plan. Read the new version back: it should have a number, an ID and a tag, and no traffic. Confirm the active deployment still serves the previous version.
  4. Promote to a small percentage, with the previous version taking the rest. Plan again and confirm that only the deployment resource is proposed for replacement.
  5. Send enough requests to the production hostname to see both versions, and record which version answered each one. Ten requests cannot prove a ten percent split.
  6. Raise the new version to 100 percent, then repeat the version check. The deployment ID should be new; the version ID should not.
  7. Roll back by deploying the previous version at 100 percent. Confirm a new deployment ID, the old version ID, and a recovery time you measured rather than estimated.
  8. Leave the previous version resource in configuration for one release. Remove it only after the next release has survived its own rollback window.

Expected observation. The promotion plan contains one deployment replacement, the rollback plan contains one deployment replacement, and both point at version IDs that already exist. The production hostname reports the version the deployment claims, and the previous version is still listed by the API.

Failure checks. The lab fails if a plan replaces a version during promotion, if the observed version differs from the deployment record, if the rollback needs a new upload, or if the only evidence is a screenshot of a success message.

Cleanup. Remove the lab version resources only after traffic is back on the version you intend to keep. Removing a version or deployment resource does not delete it in Cloudflare, but deleting the Worker does remove the script, so do that last and only when its bindings and Durable Object namespaces are unused.

Evidence to keep. The artifact digest, the version IDs on both sides of the promotion, the deployment IDs, and one request log that names the version that answered.

The release record is three IDs and one digest. Version ID, deployment ID, previous version ID, artifact digest. Everything else, including the tag and the commit message, is commentary. A release process that can produce those four values on demand can promote and recover without guessing, which is the only delivery property that survives an incident.

Next in the Series

In Worker Bindings, Secrets and Configuration Ownership, we'll explore Wire application capabilities to infrastructure IDs without configuration drift or unverified secret guarantees.