Back to Terraform

Terraform Meets Cloudflare: Provider Versions, Accounts and Tokens

November 6, 2026 Wasil Zafar 21 min read

Establish explicit account and zone boundaries and verify the provider schema before writing Cloudflare configuration

Table of Contents

  1. Map Accounts, Zones and Product Resources to Ownership
  2. Start from Current Provider V5 Schemas
  3. Use Scoped API Tokens and Separate R2 Credentials
  4. Verify Available Resources Instead of Assuming API Parity
  5. Prepare a Disposable Account or Delegated Test Zone

Map Accounts, Zones and Product Resources to Ownership

Cloudflare exposes two management scopes, and Terraform inherits both. An account owns identity, billing, members, API tokens, and the products that are not tied to a hostname. A zone owns one domain's DNS and edge configuration. The provider does not choose a scope for you; every resource declares the account or zone it belongs to.

Account-scoped resources are the shared layer. R2 buckets, Workers scripts, Pages projects, Access applications, Logpush jobs, account rulesets, load balancer pools and monitors, and account members all live under an account ID. They can serve many zones at once, so a change to one is a change to a shared dependency, not a change to one site.

Zone-scoped resources are the per-hostname layer. DNS records, zone settings, zone rulesets, cache rules, TLS settings, and most traffic controls take a zone ID. Two zones in the same account share the account layer but not their DNS or edge rules, which is why a zone-scoped token can be a useful blast-radius limit.

A zone is also a resource. Creating a zone is an account-level act: the zone resource takes an account object and a name. After creation, most work uses the zone's ID, and the zone becomes the boundary that the rest of the configuration references.

Shared failure domains are easy to miss because they look like features. One Access application can protect hostnames in several zones. One load balancer pool can serve several zones. One account ruleset can sit in front of every zone's traffic. A bad change there is not contained by a zone boundary.

Separate accounts are the clearest hard environment boundary Cloudflare offers for these shared products. Cloudflare's own best-practice guide recommends separate accounts for staging and production, precisely because account-level objects cannot be isolated inside one account. A zone boundary limits DNS and edge changes; it does not limit R2, Workers, Access, or account rulesets.

Token scope follows the same split. A zone-scoped token can read or edit the zones you list, but it cannot manage account-level products. An account-scoped token can reach selected zones and account resources, so it needs tighter review. Neither type changes what the resource schema requires; scope only limits which calls succeed.

Record the owner with the object. Note whether the account or the zone owns it, who can change it, and which token is allowed. That record survives a rename and explains a failure before you read an error.

Figure 1 shows the two layers and the token boundary between them. The account sits above both zones, while the shared products sit beside the zones because they are reachable from all of them.

Map Accounts, Zones and Product Resources to Ownership
%%{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
    ACC["Cloudflare account
members, billing, API tokens"] ACC --> Z1["Zone A
example.com"] ACC --> Z2["Zone B
example.net"] ACC --> SH["Account-scoped products
R2, Workers, Pages, Access, Logpush"] Z1 --> R1["Zone-scoped resources
DNS records, settings, rules"] Z2 --> R2["Zone-scoped resources
separate DNS and edge rules"] SH --> BOTH["Shared failure domain
one change can reach both zones"] Z1 -.->|"zone token cannot manage"| SH Z2 -.->|"zone token cannot manage"| SH AT["Account token
account plus selected zones"] --> ACC ZT["Zone token
listed zones only"] --> Z1 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 ACC,BOTH primary; class Z1,Z2 secondary; class SH,R1,R2 ok; class AT,ZT warn;

Figure 2 draws the same model as a blast radius. The account is the outer boundary, the zones are separate hostname boundaries, and the account-scoped products are the shared region that a zone token cannot reach.

Account and zone scopes with a shared failure domain The account owns zones, members, tokens and account-scoped products. Zones own DNS and edge resources. A zone-scoped token cannot manage the shared account layer, and a change to the shared layer can affect both zones. Two scopes, one shared failure domain Cloudflare account members, billing, API tokens, zone ownership the outer boundary a zone cannot contain account-wide change Zone A DNS records zone settings zone rulesets cache and TLS settings zone_id scopes each call Zone B separate DNS records separate edge rules same account different hostname boundary zone_id scopes each call Account-scoped products R2 buckets Workers and Pages Access applications Logpush and LB pools shared by every zone Zone tokens stop at the shared layer A zone token can edit Zone A without touching the account-scoped products. A change in the account-scoped products is visible in Zone A and Zone B. Name the scope before naming the file, the state, or the token.

The practical test is deletion. If deleting the object would affect more than one hostname, it belongs to the account layer; if it affects one domain's traffic or records, it belongs to the zone layer. Apply that test before choosing a directory, state file, or token.

Names do not enforce scope. A resource named for one zone can still be account-scoped. Read the schema's required arguments rather than the resource's name; account_id and zone_id are the real boundary markers.

Start from Current Provider V5 Schemas

Version 5 is a different provider, not a cosmetic bump. Cloudflare rebuilt it from its OpenAPI specification, which changed resource names, attribute shapes, and some defaults. A tutorial that was correct for 4.x can be syntactically valid HCL and still describe a resource this release does not have.

Pin three things: the CLI, the source, and the version. This article uses Terraform 1.17.1 and cloudflare/cloudflare 5.28.1. The source matters because Terraform assumes the hashicorp namespace when you omit it, and there is no hashicorp/cloudflare provider to install. The exact version matters because a range leaves the choice to the registry whenever the lock is absent or refreshed.

The lock file is the part CI should trust. .terraform.lock.hcl records the selected version and the content hashes for each platform it has seen. Commit it, and make CI init in read-only lock mode so a missing hash fails the job instead of silently resolving a new provider.

A lock written on one platform is incomplete. Record hashes for the platforms that actually run the configuration, usually the laptop architecture and the Linux CI runner. terraform providers lock adds them without changing the selected version. A checksum failure at init is often a missing platform entry, not a corrupted download.

The old DNS resource was renamed. Version 5 uses cloudflare_dns_record, not the 4.x name you will still find in tutorials. A configuration that keeps the old name fails at validation, before any API call.

The zone argument changed. Version 5 calls it name; the older zone spelling belongs to the previous schema. Migration is not only a rename of the resource block.

The record value changed too. Version 5 uses content, while value appears in older examples. A copied block can therefore fail on two arguments even after the resource name is corrected.

Provider-level account and zone arguments are gone. In v5 the provider block authenticates; the resource block locates. That separation is deliberate: one provider instance can serve several accounts or zones, and the resource's arguments say which one. A tutorial that sets an account on the provider and omits it on the resource is describing an older model.

Do not treat the docs site as versioned truth. Product pages mix 4.x and 5.x examples, and a page's date is not a schema check. The versioned registry docs and the installed schema describe the release you pinned. When they disagree with a blog post, the pinned schema wins.

Figure 3 traces the path from declaration to a verified installed provider, with the failure branches that stop it.

Start from Current Provider V5 Schemas
%%{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["required_providers
source = cloudflare/cloudflare
version = 5.28.1"] --> B["terraform init"] B --> C{"Lock entry for 5.28.1
and this platform?"} C -->|"no"| C1["Init stops
lock or checksum mismatch"] C -->|"yes"| D["Provider 5.28.1 installed"] D --> E["terraform validate
local schema check"] E -->|"legacy argument"| E1["Unsupported argument
or wrong block shape"] E -->|"valid"| F["terraform providers schema -json"] F --> G["Inspect resources,
attributes and data sources"] G --> H["Plan against
the pinned schema"] A2["Tutorial range
version = ~> 5"] -.->|"can resolve a different 5.x"| D2["Unreviewed provider
and schema drift"] D2 -.-> E 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,D,G,H primary; class B,E,F secondary; class C ok; class C1,E1 danger; class A2,D2 warn;

The failure branches are cheap until they are not. A wrong source or missing version stops init before any schema exists. A legacy argument passes parsing and fails validation against the installed schema. A lock missing the CI platform's hash fails under read-only init; a hand-edited lock fails checksum verification. Treat a mismatch as a supply-chain signal, not an obstacle to work around.

Record the resolution, not just the constraint. Capture the CLI version, the lock entry, and the schema hash in one evidence bundle, so a later plan names the same provider binary or shows a reviewed change.

Use Scoped API Tokens and Separate R2 Credentials

Start with the API, then choose the credential. Cloudflare has one REST API but several credential families, and they are not interchangeable. A provider token authenticates Terraform's control-plane calls; an R2 key authenticates S3-style object operations; an Access service token authenticates a request through an Access application; a backend credential authenticates state storage. Reusing one for another is the mistake this section prevents.

API tokens are the default. A token combines permission groups with a resource scope, can carry an expiry and an IP restriction, and can be revoked without rotating a user's global key. The secret is shown once at creation, so it belongs in a secret manager or an environment variable injected by CI, never in HCL or a committed variable file.

Global API keys are legacy and structurally unsafe. The Global key carries the user's full permissions and access to every resource the user can reach. It cannot be limited to one zone, one account, or one product, and there is only one per user. Its presence in an old example is not evidence that it is appropriate.

Scope a token to the resources the job touches. A zone token lists the zones it may access; an account token lists the account and, when needed, specific zones. Permission groups then decide read versus edit within that scope. Account scope plus zone edit is broader than zone scope plus the same permission, even though both can change DNS.

Prefer account-owned tokens for automation. A user-owned token inherits the person's memberships and stops working when that person leaves. An account-owned token belongs to the account, but not every endpoint supports it, so check the compatibility matrix first.

The table separates the credential families by what they authenticate, not by where they are stored.

CredentialAuthenticatesScopeStore inTypical failure
API token, accountTerraform provider calls to account resources and selected zonesAccount plus permission groupsCI secret or secret managerCan read but not write, or reaches unrelated zones
API token, zoneTerraform provider calls to one zone's DNS and edge settingsListed zones plus zone permissionsA secret path per zone or jobPlan passes, apply fails on an account resource
Global API keyLegacy access as the userEvery resource the user can reachAvoid; rotate if unavoidableNo least privilege, only one key per user
R2 S3 access keyS3-compatible object operations and an R2 state backendAccount or selected bucketsApplication or backend secret storeWorks for objects, cannot manage Cloudflare config
Access service tokenRequests to an Access-protected applicationAccount-level token, bound by policyRuntime secret storeValid at the app edge, useless to Terraform
State backend credentialReads and writes one state object and its lockOne bucket prefix or workspaceCI secret, separate from the providerTwo writers or a lost lock

The rows are deliberately not interchangeable. An R2 key cannot create a DNS record, and a Cloudflare API token is not an R2 S3 key. If a job needs both, give it both credentials with separate scopes rather than one broad credential that can do everything.

R2 keys are an S3 compatibility layer. Cloudflare issues an Access Key ID and a Secret Access Key from the R2 dashboard, and S3 clients use them against the account's R2 endpoint. The permission covers buckets and objects, not zones, Workers, or Access. Creating the key requires R2 to be enabled, which is an entitlement check before it is a permission check.

Access service tokens are runtime credentials. Terraform can create one as a resource, and its client ID and secret are what a machine presents to an Access-protected hostname. That secret is sensitive state, and it is not a substitute for the provider token. A pipeline that deploys a Worker and then calls the Worker needs two different credentials.

Backend credentials belong to the state boundary. The S3-compatible backend, HCP Terraform, or another backend authenticates separately from the provider; the prerequisite article on remote state covers locking and isolation. Give the backend access to one state object and its lock, and give the provider access to the resources. A provider token with state-bucket permissions is a sign the boundary was skipped.

Do not let Terraform manage its only credential. A bootstrap token creates the first token resource, and a break-glass path must exist outside the configuration. If the configuration revokes the token it is running under, the next apply cannot authenticate, and recovery depends on the dashboard or a separate admin identity.

One credential per job is the rule. Use a read-only token for plan, a write token for apply, a separate backend credential for state, and R2 or Access credentials for the application. Each secret has one audience, so the audit is simple.

Verify Available Resources Instead of Assuming API Parity

An API endpoint is not a Terraform resource. Cloudflare can ship a product endpoint before the generated provider exposes a resource, an import path, a data source, or a write-only field. The provider's schema is the contract for the release you installed; the API reference describes a different surface.

Ask five questions for every resource you plan to use. Does the resource type exist in this provider version? Do its required arguments match the values you have? Can it be imported, or must it be created? Is there a data source for reads and lists? Does it accept write-only values, or will secrets be stored in state?

The schema command answers the first two, and frames the rest. After init, terraform providers schema -json emits the installed provider's resource and data-source schemas. It proves that a resource type exists and how its arguments are classified: required, optional, computed, or deprecated. It does not prove import support, list support, write-only handling, or that the API will accept the value.

The widget pins the versions, writes a lock for both platforms, dumps the schema, and asks three concrete questions of the JSON.

terraform {
  required_version = "= 1.17.1"

  required_providers {
    cloudflare = {
      source  = "cloudflare/cloudflare"
      version = "= 5.28.1"
    }
  }
}

variable "cloudflare_api_token" {
  type      = string
  sensitive = true
}

variable "cloudflare_zone_id" {
  type = string
}

provider "cloudflare" {
  api_token = var.cloudflare_api_token
}

resource "cloudflare_dns_record" "www" {
  zone_id = var.cloudflare_zone_id
  name    = "www"
  type    = "A"
  content = "192.0.2.10"
  ttl     = 300
  proxied = false
}
terraform init
terraform providers lock -platform=linux_amd64 -platform=darwin_arm64
terraform init -lockfile=readonly
terraform validate
terraform providers schema -json > cf-schema.json

jq -r '.provider_schemas["registry.terraform.io/cloudflare/cloudflare"].resource_schemas | keys[]' cf-schema.json | grep -x 'cloudflare_dns_record'
jq -r '.provider_schemas["registry.terraform.io/cloudflare/cloudflare"].resource_schemas.cloudflare_dns_record.block.attributes | to_entries[] | select(.value.required == true) | .key' cf-schema.json
jq -r '.provider_schemas["registry.terraform.io/cloudflare/cloudflare"].data_source_schemas | keys[]' cf-schema.json | grep -x 'cloudflare_dns_records'

The first query is a presence check, not a parity check. If the resource name is absent, the provider cannot manage it, regardless of what the API supports. The exact-name grep matters because cloudflare_dns_record and cloudflare_dns_records are different surfaces.

The second query exposes required arguments for this release. It is how you catch a tutorial that omits a now-required field or uses an old attribute name. Read the output against your variables; do not infer requirements from a blog post.

The third query answers a different question: is there a read or list surface? A data source can support planning and drift checks without granting write access. If the query returns nothing, the provider may still manage the resource but cannot enumerate it, so an import workflow needs the identifier from elsewhere.

Import, list, and write-only are separate capabilities. A resource can exist and still lack import support, a data source can exist without covering every field, and a secret can be accepted without being write-only. The schema tells you what the provider models; the versioned resource docs and a disposable test tell you what the API path supports.

Test the capability where a failure is free. A read-only plan against a disposable zone proves the token can read; one create and destroy proves the write and cleanup paths. A failed import in production can duplicate or detach an object.

Figure 4 shows the gate between an API reference and a usable Terraform capability. Each checked property is a separate claim, and a missing one changes the design rather than the command.

Four gates between an API endpoint and a Terraform capability An API reference entry passes through resource-schema presence, attribute shape, import support, and read or write-only capability checks. A failure at any gate leaves the capability unverified. API availability is not a Terraform capability Check the installed schema and docs What the check proves API reference endpoint exists field documented product enabled no Terraform guarantee A published API can still be ahead of the provider or behind its import path. Resource type in schema? exact name, this release Attributes match? required, computed, nested Import path tested? create-only or adoptable Read or write-only? data source, secret handling resource exists can be planned argument contract values are valid adoption path import or create read or secret path no hidden state leak A missing gate is a design change, not a reason to fake parity with a raw API call.

A missing capability changes the design. No import path means a create-and-cutover. No data source means passing the identifier as an input. No write-only field means deciding whether the secret may enter state, or using an ephemeral mechanism instead.

Do not fake parity with a generic HTTP call. A wrapper that calls the API directly bypasses the schema, plan diff, and state model. It can be a deliberate escape hatch, but it is not Terraform support and needs its own authentication and idempotency review.

Prepare a Disposable Account or Delegated Test Zone

The lab needs a boundary it is allowed to break. Use a disposable account, or a delegated zone in an existing account where you have explicit permission and no shared production products. Record who can revoke that access before you create anything.

Lab

Verify the Cloudflare boundary

Status: design-only. No Cloudflare account or billable product was used here, and the widget's commands were not executed. The trace is written for a disposable account and ends with the evidence list.

Delegated control. Confirm three things in writing: the account owner, the zone owner, and the person who can revoke the token. A delegated zone is not a sandbox if account-level products are shared with production.

Entitlements before permissions. Check that the products in scope are enabled: R2 requires activation, Access requires a Zero Trust setup, and some ruleset or load-balancing features depend on plan. A permission group cannot grant a product the account has not bought.

Exact versions. Record Terraform CLI 1.17.1, provider 5.28.1, the lock-file hash, and the schema file's SHA-256. Without those four values, a later difference cannot be attributed to the configuration.

The trace.

  1. Create or receive the disposable zone. Record the account ID and zone ID in the evidence file, and redact them before publishing. Do not import or edit any existing production zone.
  2. Create two tokens: an account read token for the account-level inventory, and a zone token with DNS edit plus zone read for the test zone. Store each in a separate secret path.
  3. Run the pinned init and the schema queries from the previous section. Save the sanitized resource list and the required-attribute output; do not save the raw token.
  4. Run a read-only plan with the zone token. Expected result: a plan for one DNS record in the test zone, with no account-level resources in the diff.
  5. Apply the record, then query the zone's authoritative nameservers and the Cloudflare API for the same record. Both must agree before you call the write successful.
  6. Run terraform destroy and confirm the record is gone while the zone remains. Then revoke both tokens and delete the schema, plan, and local state files.

Expected result. The read-only plan must fail if you swap in the zone token for an account resource, and the apply must succeed only for the record the zone token owns. That pair of observations is the boundary proof: scope is enforced by the API, not by the directory name.

Cleanup is independently verifiable. Destroy removes managed objects, but it does not revoke tokens, delete the zone, or clear state history. Check each separately: the lab's state list should be empty, both tokens should show revoked, and a delegated zone should still exist.

Evidence to keep. The pinned versions, the lock entry, a sanitized schema summary naming the resource and its required arguments, the account/zone/permission table, both token scopes, the plan and apply transcripts, the authoritative DNS answer, and the revocation record. Redact account and zone IDs before the evidence leaves your team.

Next in the Series

In DNS as Code: Zones, Proxied Records, Delegation and DNSSEC, we'll explore Manage DNS ownership with stable record addresses and verify changes at authoritative and recursive resolvers.