Partition Roots by Account, Zone and Product Ownership
Two roots can own one object without either one being wrong. A platform team kept load balancer pools in a shared services root. The payments team kept its load balancer in a zone root. Every Monday the zone plan proposed to change the pool back to the origin it already had, and every Tuesday the shared plan proposed the opposite. Nobody had edited anything. The boundary had been drawn around folders rather than around objects.
Partition by object, not by folder
Two roots that look separate in the repository still collide if they write the same remote object. Draw the boundary from the API graph — account, zone, product, phase — and give each object exactly one address before splitting anything into folders.
The partition follows the API's object graph. Cloudflare's guidance starts with account, zone and product, and extends rulesets down to the phase level. That is not filing advice. The API is actually shaped that way: account objects contain zones, zones contain products, and product APIs return whole ordered lists. A root that ignores the graph will eventually contain two writers for one object.
Account scope is where sharing becomes invisible. Account members are zoneless, and an API token is an account object even when its policy names one zone. Load balancer pools and monitors, account rulesets, Logpush jobs at account scope, R2 buckets, Workers and Access applications are also account resources. Two zones can reference the same pool, so a pool edit is a cross-zone change even when only one zone appears in the diff. Cloudflare recommends separate accounts per environment for this reason: several account-level products cannot be isolated inside one account.
Zone scope carries the name and the certificate. DNS records, DNSSEC, zone settings, TLS mode and zone rulesets belong to one zone. DNSSEC is the sharp edge. A wrong key or delegation record affects the whole domain, so it belongs with the zone root and never in a root that manages individual records.
Rulesets make the ownership rule concrete. A ruleset resource owns the entire ordered list for one phase. Two roots that both manage the WAF custom phase do not merge their rules; the later apply replaces the list and the earlier owner's rules disappear. Split at the phase boundary, and let exactly one root own each phase.
Access is account-scoped even when the hostname is not. In provider 5.x, Access applications and policies are account-level, and a policy no longer accepts a zone identifier. Putting them in a zone root works until a second zone needs the same application. Give identity its own root, or place it deliberately in the account root.
Figure 1 turns those scopes into a decision tree with the failure branches attached.
%%{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["Account with several zones
and several product teams"] --> Q{"Who can change this object
without asking another team?"}
Q -->|"account, shared"| ACC["Account root
members, tokens, pools, Logpush"]
Q -->|"one zone"| Z["Zone root
DNS, DNSSEC, TLS, cache settings"]
Q -->|"one phase in one zone"| P["Product root
WAF, redirect or origin phase"]
ACC --> S["Shared layer
pools and monitors"]
Z --> D["Zone authority
delegation and DNSSEC"]
P --> R["One ruleset per phase
the ordered list has one owner"]
S --> F1["Failure: one pool
edited by two roots"]
D --> F2["Failure: DNSSEC moved
into a record root"]
R --> F3["Failure: two roots
replace one phase"]
F1 --> BAD["Plans flap
the last apply wins"]
F2 --> BAD
F3 --> BAD
BAD --> FIX["Split by object,
then split by phase"]
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,Q primary;
class ACC,Z,P secondary;
class S,D,R,FIX ok;
class F1,F2,F3,BAD danger;
A root is also a permission boundary. Every root deserves its own apply identity, scoped to the account or zone it changes. A plan identity that can read one state key and one zone is a smaller incident than a token that can read every zone in the organisation. If a root's token can change an object outside the root, the partition is documentation rather than a control.
Figure 2 maps the same partition onto the objects themselves, including the shared layer that zones reference but do not own.
The review test is overlap, not tidiness. Inventory every resource address with its state key, then look for an object that appears in two roots. One duplicate is a real finding even when both plans are currently empty, because the next change to either side will produce the fight the story opened with.
Choose Thin Modules Only Where They Add a Clear Contract
Cloudflare's own advice is to avoid modules, or use them sparingly. The best-practices page gives the mechanism rather than a style preference: an internal module change can leave resources out of sync or force replacements, and logic bugs inside HCL sit outside Terraform core and the provider. Dynamic blocks carry the same warning, because they are evaluated on every plan.
A module earns its place by adding a contract, not by removing lines. A contract means stable inputs, stable outputs, one subject, predictable addresses and a test that fails when the interface moves. If a module only saves typing, it adds a layer a reviewer has to simulate in their head.
A module is a contract
A module earns its place with stable inputs and outputs, one subject, predictable addresses and a test that fails when the interface moves. If it exists only to shorten the root, it has added a layer that every reviewer must now simulate.
The contract starts with what the caller supplies. Account and zone identifiers should be inputs. Provider configuration should stay in the root, with aliases passed explicitly when a module must use more than one. A module that discovers its own account or zone has an implicit input that no plan diff can show.
One wrapper over unrelated products is the anti-pattern. A module that takes a domain and creates DNS, a WAF ruleset and a Worker looks convenient in a tutorial. In production, one variable change touches three products with three failure modes, and the plan diff no longer tells a reviewer which product moved. It also merges three blast radii into one state key.
Thin does not mean trivial. A record set for one hostname, an Access application with its policies, or a Worker version with its deployment each make a good module: one subject, one contract, one failure mode, one test. The module can be deleted or versioned without touching an unrelated product.
Version the interface like code. Callers should pin a tag or commit, not a branch. When an input or output changes, the module release notes should say which caller addresses move. Inside the module, moved blocks keep addresses stable; across a major version, the caller needs to see a plan before merging.
Figure 3 shows where a module passes the contract test and where it should be replaced by direct resources.
%%{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["Same pattern repeated
in two or more roots?"] -->|"no"| RAW["Write the resources directly
the plan stays readable"]
A -->|"yes"| C{"Same inputs, outputs and
failure mode every time?"}
C -->|"no"| OPAQUE["Do not publish a wrapper
over unrelated products"]
C -->|"yes"| THIN["Thin capability module
one subject, one contract"]
THIN --> PIN["Pin source and version
pass identifiers in and out"]
PIN --> TEST["Contract test with
a mocked provider"]
TEST --> OK["Caller plan shows
product-level addresses"]
THIN --> L1["Failure: module discovers
its own account or zone"]
THIN --> L2["Failure: one wrapper owns
DNS, WAF and Workers"]
L1 --> D1["A zone change looks
like a no-op in review"]
L2 --> D2["One variable touches
three products at once"]
OK --> GATE{"Does the module add a
contract a reviewer can name?"}
GATE -->|"no"| RAW
GATE -->|"yes"| KEEP["Keep it thin and
version the interface"]
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,GATE primary;
class THIN,PIN,TEST secondary;
class RAW,OK,KEEP ok;
class OPAQUE,L1,L2,D1,D2 danger;
A module that hides an identifier creates drift that looks like a no-op. The clearest example is a module that derives a record name from a display label. Rename the label, and the module replaces the record while the caller's diff reads as a one-word change in a child module. The reviewer approves a rename and gets a new DNS target.
Delete modules that fail the sentence test. Complete this sentence before adding one: the module exists so a caller can do a specific thing without repeating a specific set of resources. If the sentence needs two products or three audiences, the module is a wrapper, and the resources belong in the root where the plan can show them.
Test DNS, TLS, Access, Caching and Worker Bindings Independently
Five surfaces fail in five different ways. DNS fails by resolution, TLS by trust, Access by bypass, caching by a wrong hit, and Worker bindings by a name that resolves to nothing or to the wrong object. A single smoke test that checks for a 200 sees none of the five causes.
Static and mock tests run on every pull request. Formatting, validation and native Terraform tests with a mocked provider need no token and no account. They prove that the configuration is well formed, that variables satisfy their validation rules, and that a module's inputs and outputs still line up. A plan-only test run can assert addresses and attribute values without creating anything.
A plan test proves the graph, not the edge. It cannot prove that the token has the right permission, that the account is entitled to the product, or that the origin certificate chains correctly. Those are API and runtime facts, and they only appear against a real zone.
Sandbox tests need a disposable zone and a scoped token. Use an account or zone created for the lab, give the token write access only there, and tear the objects down at the end. Production credentials turn an acceptance test into an incident with a test name.
DNS and TLS are separate contracts. A DNS test asserts that the name resolves to the intended target with the intended proxy setting. A TLS test asserts that the origin chain validates under strict mode and that the certificate covers the hostname. A self-signed origin must fail strict mode; a test that only reads the mode string proves nothing about trust.
Access and caching are behavioural. For Access, an unauthenticated request must be challenged and a path outside the policy must not return content. For caching, the response header is the evidence, not the rule attribute. A response that sets a cookie, or a path that must bypass the cache, belongs in the negative set.
Worker bindings are easy to fake and expensive to get wrong. A mocked provider will accept any binding name. A real test deploys a version, calls the route, and asserts that the binding name resolves to the expected object. Removing a binding should fail the first call, and pointing it at a different bucket should return different data.
The matrix below keeps each surface honest about which layer proves what.
| Surface | What mocks and plan prove | What only the sandbox proves | Negative test to keep |
|---|---|---|---|
| DNS | address wiring and rendered name, type and content | the API accepts the name and the record resolves through the edge | a duplicate name or a record in the wrong zone is caught in review |
| TLS | mode and minimum version appear in the diff | the origin chain validates under strict mode and the certificate covers the hostname | a self-signed origin is rejected rather than silently downgraded |
| Access | application, policy and audience references are complete | unauthenticated traffic is challenged and no bypass path returns content | a path outside the policy returns a challenge, not the origin |
| Caching | phase, expression and action survive the plan | the response header shows the expected cache status at the edge | a cookie-bearing response or a bypass path is not cached |
| Worker bindings | binding names and types match what the code expects | the deployed version calls the binding and reaches the intended object | removing a binding fails the first call, not the deployment |
The negative test is the one that survives an incident. Positive tests confirm the happy path you just built. Negative tests encode the assumption that made the design safe: no bypass, no downgrade, no cache leak, no silent missing binding. Keep one per surface in the required check set.
Build Artifact and Infrastructure Promotion into One Reviewable Record
Two artifacts leave the build, and they must travel together. One is the plan; the other is the Worker bundle or container image the plan refers to. A plan approved against bundle A and applied with bundle B is an unreviewed deployment with a reviewed filename.
Pin the producer before trusting the product. Terraform 1.17.1 and provider 5.28.1 belong in the version constraints and in the workflow that runs them. The provider lock file is committed, modules are pinned to a tag or commit, and third-party actions are pinned to a full commit hash. A plan is evidence only when the tool that produced it is fixed.
Record facts a reviewer can check, not a narrative. The record needs the commit and tree, the CLI version, the provider lock digest, the module references, the state key, the plan digest and the bundle digest. Add the account or zone placeholder, the approver, the creation time and an expiry. Values never belong in the record, only the digest of the inputs.
Build once and promote by digest. Rebuilding per environment can change a transitive dependency and produce a bundle that was never tested. For Workers, the version resource tracks content with a computed hash, and file-based module content is preferable to inline content because it keeps large bundles out of state. The digest is what moves from staging to production.
Worker versions are immutable and append-only. A code change creates a new version; the deployment moves traffic to it. The old version is not deleted when a replacement happens, and deleting the parent Worker deletes the whole history. A healthy plan for a code change shows a version creation and a deployment update, not an in-place edit of a script.
Choose the Worker ownership layer once. Terraform can own the Worker, its version and its deployment; it can own the Worker and deployment while CI uploads versions; or it can own only the Worker. All three are legitimate. Two tools writing the same layer are not: Wrangler and Terraform will each see the other's version as drift and produce a stream of replacements.
Re-plan when an approved input moves. A branch that moves after review, a lock digest that changes, a module tag that is re-pointed, a rotated variable that feeds a planned value, a new bundle digest, or an expired approval all invalidate the record. The apply job should verify the record before it runs, not re-plan quietly to make the inputs match.
Plan artifacts contain variable values in cleartext. Encrypt the stored plan, keep it for days rather than months, and give it a named reader list. Publish the summary — counts, replacements, risky resource types and the two digests — in the review, and keep the binary in the protected store.
Diagnose API Limits, Normalization and Partial Applies
The first failure is usually a quota, not a bug. Cloudflare's global limit is 1,200 requests per five minutes per user or account token, with a separate per-IP limit of 200 requests per second. Exceeding the global limit blocks all API calls for the next five minutes, including calls from the dashboard and from other pipelines using the same identity.
The quota is shared, so the blast radius is shared. One large plan that fans out hundreds of resources can starve an unrelated deployment and a human debugging in the dashboard. That is an argument for separate tokens per pipeline, bounded parallelism, and treating a 429 as a scheduling problem rather than a provider defect.
Read the response before choosing a delay. A throttled response carries a retry-after value, and the rate-limit headers report the remaining quota and the reset time. Provider 5.28.1 exposes no retry or backoff arguments in its schema, so the workflow cannot tune retries through provider configuration. Bound the attempts at the job level, honour the header, add jitter, and stop after a small number of tries.
A second apply is a new decision, not a retry. After a failure, Terraform has already written state for the resources that completed. Repeating the same apply can duplicate a create, hit an already-exists error, or move traffic to a version nobody reviewed. Stop the pipeline first, then diagnose.
Normalization produces a permanent diff, not drift. The API returns canonical values: settings as on or off strings, names in a normalized form, lists in the service's order. A plan that reports the same small change after every apply is usually comparing the configuration to the canonical form. Fix the configuration or add a narrow, documented exception; removing the resource from state hides the disagreement instead of resolving it.
A partial apply leaves three views that disagree. State records what completed, the API records what exists, and the configuration records what was intended. A Worker version can exist while the deployment still points at the previous one. An Access application can exist without its policy. The failed resource may be tainted, which turns the next plan's replacement into a data-loss instruction if the object holds data.
Figure 4 separates the three failure shapes and the two responses that make them worse or better.
Diagnose in a fixed order. Stop writers, capture the failing run and the state serial, identify the first error, check the quota headers, run a refresh-only plan to read the real state, then a normal plan. Inspect logs through a private channel and sanitise account identifiers and tokens before sharing a snippet.
Some ordering failures are designed in. A Durable Object binding cannot resolve before a deployment has applied its migration. Cloudflare documents the two-phase workaround, and it is also a legitimate reason to let Terraform own the Worker and deployment while another tool owns versions. The failure is not a provider bug; it is an ownership choice that has to be made explicitly.
Prove Drift, Recovery and Project-Owned Cleanup
Drift is a signal with three possible meanings. Someone changed the edge from the dashboard, the provider normalized a value, or another tool owns part of the object. Classify before acting. A scheduled read-only plan per root, run on detailed exit codes, turns a change into a ticket rather than an automatic apply.
Acceptance is a no-change plan per surface, not a green apply. Re-plan immediately after apply and expect no changes. A persistent diff means normalization, a provider default or a missing dependency. That is the moment to fix the configuration or record an exception, while the change is still fresh.
Recovery needs a name, not a team alias. The runbook should name who can approve a re-apply, where the break-glass token lives, how state is restored, and who confirms that no writer still holds the lock. The state-locking article covers the mechanism; this record covers the human path through it.
Cleanup belongs to the project that created the objects. Destroy the roots in dependency order, empty R2 buckets before deletion, remove Access applications and policies, revoke the lab tokens, and delete stored plans. A Worker deletion removes its versions, which is convenient for a lab and dangerous in production, where the history is part of the audit trail.
Keep a per-surface evidence set. Plan identity, test results, runtime probes, the drift report and the cleanup log. A single green pipeline run is not the same as five surface checks plus a final no-change plan.
The lab builds that record without touching a Cloudflare account.
Review the Cloudflare delivery workflow
Execution status: design-only. Terraform CLI 1.17.1 and cloudflare/cloudflare 5.28.1 were current on 6 November 2026. No Cloudflare account, token or pipeline run is used; every identifier below is a placeholder.
Prerequisites. Terraform CLI 1.17.1, Git, a text editor, and read access to one CI configuration. Optional: a disposable Cloudflare sandbox zone if you later choose to execute any step. Do not use a production zone.
Records to produce.
| Record | What it holds |
|---|---|
| roots.md | root path, scope, state key, owner, apply identity, shared objects it references |
| modules.md | each module, the contract it adds, its callers and its version pin |
| test-matrix.md | surface, mock or plan check, sandbox check and negative test |
| promotion.md | commit, CLI, provider lock, module refs, plan digest, bundle digest, approver, expiry |
| recovery.md | drift class, reconcile path, named recovery owner, cleanup order |
Steps.
- Inventory the roots. One row per root and state key, with the account, zone or phase scope. Mark every account-level object referenced by more than one root; a shared pool with two writers is the first finding.
- Draw the ownership map. Put the account band above the zones and the ruleset phases inside one zone. Draw a crimson line wherever a root would need to write outside its column.
- Write the sentence test for every candidate module. Keep the ones that name one subject and one contract; inline the rest. Record the module version pin and the caller addresses it owns.
- Build the test matrix. For each of the five surfaces, write one mock or plan check, one sandbox check and one negative test. Mark the sandbox column "not run" if you have no disposable zone.
- Write the promotion record with a real structure and placeholder values. Include the plan digest and the bundle digest, and state which Worker layer Terraform owns.
- Tabletop a 429 at resource 40 of 120. Write what the job does, how long it waits, and what it does not retry. Include the retry-after value as a placeholder.
- Tabletop a partial apply where the Worker version exists and the deployment still points at the previous version. Write the state view, the API view, the config view and the next action.
- Tabletop cleanup. Name the destroy order, the empty-bucket step, the token revocations and the plan-artifact deletion.
Expected observation. An ownership map with no object written by two roots, a module list where every entry passes the sentence test, a five-surface test matrix with one negative test each, and a promotion record that a reviewer can check without reading a raw plan.
Failure checks. The design fails if a shared pool has two writers, if a module discovers its own account or zone, if the test matrix has no negative test, if the promotion record omits the bundle digest, or if recovery begins with a second apply.
Cost dimensions. Zero. No Cloudflare calls and no stored artifacts beyond the design documents.
Cleanup. Delete the lab directory, or keep it as a reviewed design with placeholders intact. If you executed any step against a sandbox, destroy the objects and revoke the token.
Evidence to keep. The roots inventory, the ownership map, the module sentence list, the test matrix, the promotion record and the recovery runbook.