Tokens and SDKs Need Explicit Resource Scope
A deploy script works on a laptop and fails in CI with Authentication error. The code is unchanged; the credential is not. The laptop likely used a personal token with broad access, while CI received a token for another account or one that can edit DNS but not Workers. That is a scope bug, and it is the first thing to make explicit.
Think of a hotel key card. It encodes three separate facts: who you are, which doors you may open, and when the card stops working. A Cloudflare API token is that card: a permission set, a resource boundary, and optional restrictions such as an expiry time or an IP range.
Vocabulary first:
Token, permission, scope
An API token is a secret presented as Authorization: Bearer <token> to the Cloudflare API v4 endpoint. A permission group is the verb — DNS Read, Workers Scripts Edit, Workers Routes Edit — and a scope is the noun: the account, zone, or user resource the verb applies to. Both must allow the request, and Edit covers create, read, update, delete, and list.
The credential type decides who the token acts for and whether it survives a staff change:
| Credential | Acts as | Survives staff changes | Prefix | Best for |
|---|---|---|---|---|
| User API token | The person who created it, with a subset of their permissions | No — revoked when the person leaves or changes role | cfut_ | Local checks and short-lived personal automation |
| Account-owned token | A service principal, independent of any one person | Yes | cfat_ | CI pipelines and long-lived integrations |
The secret is shown once at creation. Cloudflare publishes a compatibility matrix because some products do not support account-owned tokens yet.
An SDK wraps the REST API; Cloudflare publishes Go, TypeScript, and Python SDKs. Infrastructure as code (IaC) is a declarative description of desired resources plus a tool that compares it with reality. State maps a configuration address such as cloudflare_dns_record.demo to a remote object ID and last-read attributes. Drift is any difference among state, configuration, and the live resource. Idempotency means repeating a request produces the same end state as sending it once.
The mental model is a chain: principal → permission → resource scope → secret handling → transport → rate limit. Each link can reject independently. Figure 1 shows where.
%%{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
U[Operator or CI job] -->|Bearer token| V{Token valid and unexpired?}
V -- no --> E401[401 authentication error]
V -- yes --> P{Permission group allows the verb?}
P -- no --> E403[403 authorization error]
P -- yes --> S{Resource is inside token scope?}
S -- no --> E403
S -- yes --> API[Cloudflare API v4]
API --> L{Rate limit available?}
L -- no --> E429[429 and retry-after]
L -- yes --> OK[Change accepted]
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 S,API primary;
class U,L,E429,OK secondary;
class P ok;
class V,E401,E403 danger;
A valid token can still be the wrong token
Granting Zone DNS Edit on all zones when the job needs one is over-scoped. Giving CI a personal token is fragile: it disappears when the employee changes roles. Start with the smallest permission set that passes, scope it to named resources, set a TTL, and put the secret in the CI secret store rather than a repository variable. For a service integration, prefer an account-owned token.
Figure 2 separates the layers so a failure can be assigned to the right one: the secret store, the token policy, the API, and the account/zone/resource hierarchy.
SDKs are convenience, not a different security model. A typed SDK signs the same requests with the same token and hits the same limits as curl; use it to chain calls, handle typed errors, or integrate with an application. Cloudflare's SDKs read the rate-limit headers and back off automatically.
The documented global limit is 1,200 requests per five minutes per user or per account token, plus 200 requests per second per IP. Exceeding it blocks calls for five minutes and returns HTTP 429 with a retry-after header (rate limits). A large Terraform plan can read hundreds of resources, so a pipeline that also polls the API aggressively can throttle itself.
Retries need care. Cloudflare documents Idempotency-Key for specific endpoints, such as account creation, not as a blanket guarantee for every POST. Treat create calls as non-idempotent unless the endpoint says otherwise; that explains most duplicate-resource incidents later.
Wrangler and IaC Should Not Fight Over Ownership
Two people editing the same document without ownership rules produce a predictable result: each save silently removes the other's work. Wrangler and an IaC tool can do the same to a Worker. The fix is to assign ownership per object, in writing, rather than to pick one tool forever.
Give each object exactly one owner, in writing. Suppose you need to move www.example.com to a new origin and route traffic through a Worker. Wrangler should bundle the code, upload a version, and shift the deployment. Terraform or Pulumi should own the DNS record and the Worker's identity. Give the route one owner: either the IaC tool or Wrangler's routes configuration, never both. If both tools also set the same route or compatibility_date, the last writer wins. Cloudflare's Workers IaC documentation explicitly supports the split: manage only the cloudflare_worker resource with Terraform and keep Wrangler for versions and deployments.
The table compares responsibilities, not brands.
| Concern | Wrangler | Terraform | Pulumi |
|---|---|---|---|
| Primary job | Bundle, upload, and deploy Worker code; manage versions and traffic | Declare and reconcile Cloudflare resources from HCL | Declare and reconcile Cloudflare resources from a general-purpose language |
| Unit of change | A version and a deployment | A resource address in state | A resource in a stack |
| Preview | wrangler deploy --dry-run for the bundle | terraform plan, with -detailed-exitcode for automation | pulumi preview, with --expect-no-changes for automation |
| State and history | Deployment and version history in Cloudflare | Local or remote state file; lock file pins providers | Stack state in a backend; encrypted secrets; plugin versions |
| Code bundling | Built in | None; bundle before upload or let Wrangler build | None; bundle in your program or pipeline |
| Best fit | Worker code, gradual releases, rollback | DNS, zones, routes, account resources, policy | Teams already using TypeScript, Python, Go, or .NET for infrastructure |
Figure 3 shows the decision and the two failure paths: overlapping ownership and an unrecorded emergency change.
%%{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','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[Change requested] --> B{Which object changes?}
B -->|Worker code or version| C[Wrangler]
B -->|Worker shell, DNS, IaC route| D[Terraform or Pulumi]
B -->|Emergency hotfix| E[Dashboard or API]
C --> F[Upload version and deploy]
D --> G[Preview or plan, then apply]
E --> H[Out-of-band change]
H --> I{Recorded in code and state?}
I -- no --> J[Drift or orphaned resource]
I -- yes --> K[Next plan reverts or conflicts]
F --> L{Also managed by IaC?}
L -- yes --> M[Overlapping ownership]
L -- no --> N[Clean deploy]
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 G,I primary;
class A,B,C,D,E,F,H,L,M secondary;
class N ok;
class K danger;
class J warn;
The two panels show the same boundary in two dialects. The bash panel has Terraform create the Worker shell and DNS record, then Wrangler deploy the code and its route. The TypeScript panel expresses the IaC half in Pulumi.
Configure the Pulumi stack before the first preview. The provider reads the token from stack config locally and from the CLOUDFLARE_API_TOKEN environment variable in CI.
Now the boundary that is easy to blur: API, IaC, or dashboard.
| Surface | Use it for | Ownership record | Failure mode |
|---|---|---|---|
| Dashboard | Exploration, one-off inspection, and emergencies when the pipeline itself is broken | None; a change to a managed object becomes drift | Codify it the same working day or lose it to the next apply |
| REST API or SDK | Glue, custom tooling, application integration, cache purges, analytics queries | None; a request leaves no intent | Good escape hatch, poor owner |
| Terraform or Pulumi | Durable ownership of DNS, routes, Workers, and account policy that should exist in every environment | Configuration, state, review, and history | Needs plan discipline and drift review |
Coverage is still not universal. Terraform plan and Pulumi preview work for resources the provider models, and Cloudflare's v5 provider is generated from the API's OpenAPI schemas, which broadened coverage considerably. Some Workers resources are explicitly beta. A clean plan proves that the modeled attributes match the configuration; it does not prove that every setting in the dashboard matches your intent.
Terraform and Pulumi Model Resource Lifecycles
Both tools implement the same loop: read configuration, refresh state from the API, compute a diff, show it, and apply it. Terraform stores the map in a state file; Pulumi stores it in a stack with a pluggable backend. State is a cache of remote IDs and last-read attributes, not the source of truth.
State is a liability, not a backup
Terraform does not encrypt state by default, so a committed terraform.tfstate can leak secrets or private configuration. Use an encrypted, locked remote backend, restrict readers, and commit only configuration and the lock file. Pulumi encrypts secret values in state, but the backend and stack access policy still need to be production infrastructure.
Locking matters because two concurrent applies can decide to create the same object, and one loses. That is a coordination failure, not a merge conflict.
Pin the provider and commit the lock file. A Terraform constraint such as ~> 5.28 accepts 5.28 and later 5.x releases but not 6.0; = 5.28.1 is an exact pin. Committing the provider lock file makes every machine resolve the same build and checksums, and the Pulumi side should pin its provider version in the project. Upgrades then become a reviewed change: read the upgrade guide, plan in a branch, and inspect replacements before production.
The v4 to v5 Terraform transition is the concrete example. V5 was a ground-up rewrite: tf-migrate rewrites configuration and generates moved blocks, and state upgraders in v5.19 and later handle much of the state side.
| Change | v4 form | v5 form | Handle with |
|---|---|---|---|
| DNS record resource | cloudflare_record | cloudflare_dns_record | tf-migrate |
| Record value attribute | value | content | tf-migrate |
| Resource type names | — | More than 40 renamed | tf-migrate |
| State addresses | v4 addresses | v5 addresses | State upgraders in v5.19 and later |
A team that pins and upgrades deliberately gets a boring migration; a team that floats on the latest version gets a surprise replacement.
Idempotency, retries, and rate limits intersect most sharply during a partial apply. An apply creates a DNS record, receives success, then fails before writing the ID to state. The resource exists; the state does not know it, so the next apply tries to create it again, producing a duplicate, a conflict, or a silent second object. Stop, inspect the remote object, and import it rather than re-running blindly. A provider retry after an unknown outcome is a new decision, not a replay.
A clean plan is not proof of parity
A clean terraform plan is not proof that the cloud matches your files. It is proof that the provider's last refresh matched the configuration for the attributes it models. Drift can exist in unmodeled settings, in resources no one imported, and in changes made after the refresh. Ownership is what closes that gap; a plan only observes it.
The same lifecycle creates the cleanup problem. A destroy deletes what the state owns; it cannot delete what the state never knew about. That is why an unmanaged DNS record or Worker can outlive its team, keep serving traffic, and keep appearing on a bill. Use prevent_destroy in Terraform or the protect resource option in Pulumi for stateful resources, and treat state loss as an incident rather than a fresh start.
Importing Existing Resources and Reviewing Drift
Import brings a resource created in the dashboard, by curl, or by a predecessor's script into managed ownership. You write the configuration address, supply the remote ID, and the tool writes the mapping into state. Import does not write configuration or make the remote object match it; it only teaches the state the object's identity.
The IDs follow the resource hierarchy. A DNS record imports by zone and record ID; a Workers route by zone and route ID; a Worker version by account, Worker, and version. Terraform 1.5 and later also supports an import block, and -generate-config-out writes HCL for imported resources not yet in configuration; HashiCorp labels that generation experimental, so review the result.
Figure 4 shows the before/after state and the failure branch that catches most first imports: the configuration does not match the remote object, so the first plan proposes a replacement rather than a no-op.
Drift review is a decision, not a reflex. A plan that shows a difference has three legitimate responses.
Accept the remote value if the out-of-band change was correct: update the configuration, or run a refresh-only apply to record the new attributes in state before changing code.
Enforce the configuration if the remote change was unauthorized: apply the plan, understanding that some attributes force replacement.
Forget the resource if it should no longer be managed: remove it from state and configuration deliberately, rather than deleting it from the dashboard and leaving a stale address.
Import writes identity, not configuration
An import with a mismatched configuration can replace a live record, and a wrong ID can attach state to the wrong object. Review the first plan after every import before applying it.
Cloudflare's Terraform guidance warns that state can break when the same resources change through Terraform and the dashboard or API. Keep plan review and ownership real; this is not a reason to avoid IaC.
Design a Reproducible Zone and Worker Configuration
This is a design-only exercise; no commands were executed and no measured result is reported. It uses an existing zone so that nameserver delegation is out of scope, and it keeps every resource on free-tier-eligible products. Verify current plan availability, Workers limits, and pricing before running it.
Design a Reproducible Zone and Worker Configuration
Status: design-only, not executed.
Prerequisites. An existing zone you control, its account and zone IDs, Terraform 1.5 or later, and Wrangler 4.x with Node 20 or later. One token, scoped to that account and zone, carries Zone DNS Edit, Zone Workers Routes Edit, and Account Workers Scripts Edit. Store it in a secret manager, never in the repository.
What you build.
| Piece | Owner | Contents |
|---|---|---|
| Terraform directory | Terraform | Pinned cloudflare/cloudflare provider, a cloudflare_worker shell named iac-lab-worker, and a proxied cloudflare_dns_record for iac-lab.<your-zone> |
| Worker directory | Wrangler | wrangler.jsonc with the same Worker name, a route for iac-lab.<your-zone>/*, a compatibility_date, and one TypeScript handler |
| The route | Exactly one of the two | Declared once, either in Wrangler or in the IaC configuration |
Steps.
| Step | Action | Confirm |
|---|---|---|
| 1 | Export the token and the account and zone IDs, then verify the token at /user/tokens/verify | The call succeeds; no 401 or 403 |
| 2 | Run terraform init and commit .terraform.lock.hcl | The pinned 5.x provider resolved |
| 3 | If the record exists, add an import block with the zone/record ID and plan with config generation | HCL reconciled by hand |
| 4 | Run terraform plan -out=tfplan | Every create, update, and replace read; no duplicate record |
| 5 | Run terraform apply tfplan | Worker shell and DNS record exist |
| 6 | From the Worker directory, run npx wrangler deploy | The route binds to the new Worker |
| 7 | Run terraform plan -detailed-exitcode | Exit code 0 |
| 8 | Change only the DNS comment in the dashboard, wait, then plan again | Exit code 2 and a one-attribute in-place update; accept or revert it |
Expected observations. The apply creates the Worker shell and DNS record; the deploy creates a version, deployment, and route; the route serves the Worker; a clean plan exits 0; the comment change produces a one-attribute diff. These are expected outcomes, not measurements.
Failure checks.
| Symptom | Likely cause | Response |
|---|---|---|
| 403 on route creation | Token lacks Workers Routes Edit, or the hostname is not proxied | Rescope the token or proxy the hostname |
| 409 or duplicate record | Wrong import ID or missing record | Recheck the ID; import before the next apply |
| State lock error | Another apply holds the lock | Confirm no apply is running before touching the lock |
| Proposed replacement | An immutable attribute changed | Read the diff before applying |
Cost dimensions. DNS, routes, and a minimal Worker fit free-tier plans at the time of writing, but request volume, plan tier, and add-ons determine the bill. Verify current limits and pricing before production traffic; no paid load balancer, certificate, or enterprise product is required.
Cleanup. Run npx wrangler delete --name iac-lab-worker to remove the Worker and its route, then terraform destroy to remove the DNS record. If destroy reports the Worker already gone, remove it from state. Confirm no record or route remains, delete the state file and plan, and revoke the lab token.
Review a Change Plan and Show a Clean No-Op Recheck
The evidence standard: explicit ownership and a genuinely clean second run.
Pass/fail evidence.
- Pass: every managed resource has one declared owner, written down.
- Pass: the CI token is scoped, TTL-bound, and stored outside the repository.
- Pass: provider version and lock file are pinned, and upgrades get a plan review.
- Pass: state is encrypted, access-controlled, and locked during applies.
- Pass: a second plan reports no changes, and the exit status reflects that.
- Pass: drift is resolved by an explicit decision, not by re-running apply until the diff disappears.
- Fail: the same route, record, or Worker setting is declared in both Wrangler and IaC.
- Fail:
terraform applyis the first response to an unknown partial failure. - Fail: a clean plan is treated as proof that unmanaged resources and unmodeled settings are correct.
Treat the exit status as the gate, not the text output. -detailed-exitcode returns 0 for an empty diff, 1 on error, and 2 when changes are present, so CI can fail on 2 without parsing text. On the Pulumi side, --expect-no-changes errors if the preview proposes any change.
Either gate is still not a substitute for the plan. A plan can be empty because the configuration is correct, or because the provider did not model the attribute. Pair the gate with a scheduled drift check that alerts on a difference.
Self-check.
A token has Zone DNS Edit on example.com, but the API returns 403 for a Workers route. Why? Permission and scope are separate checks. The token has the DNS verb on the right zone but not the Workers Routes verb; broader DNS permission does not help.
Terraform created a DNS record, then failed before writing state. What should you do before the next apply? Stop and inspect the remote object, then import it with the <zone_id>/<dns_record_id> ID and plan again. Re-applying first can duplicate or conflict, and a retry does not make the create idempotent.
A dashboard change is reverted by the next apply. Is that a bug? No. Terraform is authoritative for managed attributes; the change was drift. Codify the intended value through the pipeline, or stop managing that attribute. The fix is a break-glass procedure, not a weaker plan.
Unresolved limitations. This article was not lab-executed; every command and expected observation is a design, not a measurement. Cloudflare's surface changes faster than provider coverage, and some resources remain beta or have incomplete read behavior. Plan availability, limits, and pricing must be rechecked at run time. Import does not repair mismatched configuration, and state security depends on the backend. Rate limits are shared by every job using the same token, so parallel applies and monitoring interfere. Transport retries reduce transient failures but cannot guarantee exactly-once creation after an unknown outcome.
Verification note. Planning baseline: 2026-11-02. Verification date: 2026-11-05. Registry and release metadata checked on that date: Cloudflare Terraform provider 5.28.1, Pulumi Cloudflare provider 6.23.2, Cloudflare TypeScript SDK 7.3.0, Wrangler 4.157.0, Terraform CLI 1.17.1, Pulumi CLI 3.274.0. These are version observations, not tested combinations; no apply, deploy, or Pulumi update was run.
References. - Cloudflare API: https://developers.cloudflare.com/api/ - Cloudflare API get started and tokens: https://developers.cloudflare.com/fundamentals/api/get-started/ - Create an API token: https://developers.cloudflare.com/fundamentals/api/get-started/create-token/ - Account API tokens and compatibility: https://developers.cloudflare.com/fundamentals/api/get-started/account-owned-tokens/ - API token permissions: https://developers.cloudflare.com/fundamentals/api/reference/permissions/ - API rate limits: https://developers.cloudflare.com/fundamentals/api/reference/limits/ - API SDKs: https://developers.cloudflare.com/fundamentals/api/reference/sdks/ - Cloudflare Terraform: https://developers.cloudflare.com/terraform/ - Terraform get started: https://developers.cloudflare.com/terraform/installing/ - Terraform best practices: https://developers.cloudflare.com/terraform/advanced-topics/best-practices/ - Import Cloudflare resources: https://developers.cloudflare.com/terraform/advanced-topics/import-cloudflare-resources/ - Cloudflare Pulumi: https://developers.cloudflare.com/pulumi/ - Pulumi Worker tutorial: https://developers.cloudflare.com/pulumi/tutorial/hello-world/ - Workers infrastructure as code: https://developers.cloudflare.com/workers/platform/infrastructure-as-code/ - Wrangler configuration: https://developers.cloudflare.com/workers/wrangler/configuration/ - Terraform plan exit codes: https://developer.hashicorp.com/terraform/cli/commands/plan - Terraform import blocks: https://developer.hashicorp.com/terraform/language/import - Terraform state locking: https://developer.hashicorp.com/terraform/language/state/locking - Pulumi import: https://www.pulumi.com/docs/iac/cli/commands/pulumi_import/ - Pulumi preview: https://www.pulumi.com/docs/iac/cli/commands/pulumi_preview/
Next in the Series
In Build a Release Pipeline You Can Recover From, we'll explore Connect previews, approvals, migrations, feature flags, and rollback.