Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 36 ยท Operations and Analytics

Cloudflare API, Terraform and Automation

Automate Cloudflare with API tokens, the v4 REST API, curl and JavaScript examples, pagination, rate limits, the Terraform provider and a safe DNS change workflow with drift checks.

Clicking in a dashboard is fine for one change. When you manage ten zones, a team, or a change that must be reviewed, you want it in code. Everything in the Cloudflare dashboard is backed by the Cloudflare API, and there is an official Terraform provider built on it. This lesson shows how to authenticate, call the API, page through results and describe your configuration as code.

Calls to the real API cannot be made from this site, so API calls and Terraform are read-only. The runnable examples build requests, validate configuration and compute change plans locally.

API tokens, not global keys

Create an API token (My Profile, API Tokens). Give it only what the job needs:

  • Permissions: for example Zone / DNS / Edit to manage DNS records.
  • Resources: a specific zone or account, not "all zones".
  • Client IP filtering and a TTL (expiry) when possible.

Avoid the legacy Global API Key, which has the power of your whole account. Store tokens in a secrets manager or CI secret and pass them as environment variables, never in source control. Verify a token with:

Terminal
curl -s https://api.cloudflare.com/client/v4/user/tokens/verify \
  -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"

The REST API

The base URL is https://api.cloudflare.com/client/v4/. Every request sends Authorization: Bearer <token>. Every response has the same envelope:

JSON
{
  "success": true,
  "errors": [],
  "messages": [],
  "result": [ /* data */ ],
  "result_info": { "page": 1, "per_page": 20, "total_count": 57, "total_pages": 3 }
}

Always check success and read errors (a list of { code, message }). Common tasks:

Terminal
# find your zone id
curl -s "https://api.cloudflare.com/client/v4/zones?name=example.com" -H "Authorization: Bearer $TOKEN"

# list DNS records (page 1, 100 per page)
curl -s "https://api.cloudflare.com/client/v4/zones/$ZONE/dns_records?per_page=100&page=1" \
  -H "Authorization: Bearer $TOKEN"

# create an A record
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE/dns_records" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  --data '{"type":"A","name":"app","content":"203.0.113.10","ttl":1,"proxied":true}'

# purge cached files by URL
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE/purge_cache" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  --data '{"files":["https://example.com/app.css"]}'

ttl: 1 means "automatic". Rate limits apply (on the order of a thousand requests per five minutes per token; check the current figure), and on a 429 response you should wait for the Retry-After header and retry.

A client helper with pagination and retry

Here is the shape of a robust client in JavaScript. The runnable version below replaces the network with a fake so you can watch pagination and retry work.

JavaScript
async function cf(path, { method = "GET", body } = {}) {
  for (let attempt = 1; attempt <= 3; attempt++) {
    const res = await fetch("https://api.cloudflare.com/client/v4" + path, {
      method,
      headers: { Authorization: `Bearer ${process.env.CF_TOKEN}`, "Content-Type": "application/json" },
      body: body ? JSON.stringify(body) : undefined,
    });
    if (res.status === 429) { await new Promise((r) => setTimeout(r, 1000 * attempt)); continue; }
    const json = await res.json();
    if (!json.success) throw new Error(json.errors.map((e) => e.message).join("; "));
    return json;
  }
  throw new Error("rate limited");
}
JS Pagination and retry against a fake API

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Terraform

The Cloudflare Terraform provider manages zones, DNS, rulesets, Workers, Access, tunnels and more as declarative resources. You describe the state you want; Terraform computes the difference and applies it, and the plan is reviewable in a pull request.

HCL
terraform {
  required_providers {
    cloudflare = { source = "cloudflare/cloudflare", version = "~> 5.0" }
  }
}

provider "cloudflare" {
  # reads CLOUDFLARE_API_TOKEN from the environment
}

variable "zone_id" { type = string }

resource "cloudflare_dns_record" "app" {
  zone_id = var.zone_id
  name    = "app"
  type    = "A"
  content = "203.0.113.10"
  ttl     = 1
  proxied = true
}

Resource and attribute names changed between provider major versions (version 5 renamed several resources and attributes compared with version 4), so always check the provider documentation for the version you pin. Workflow: terraform init, terraform plan, review, terraform apply. Keep state in a remote backend (R2 works through the S3 backend). If someone edits a record in the dashboard, the next plan shows drift, which you either adopt into code or revert. Existing resources can be brought under management with terraform import or the cf-terraforming tool, which generates configuration from what already exists.

The next example computes a plan the way Terraform does: compare desired records with actual ones.

JS Plan DNS changes (desired vs actual)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Other ways to automate

  • Wrangler and the Workers APIs for deployments (covered earlier in this chapter).
  • GitHub Actions: cloudflare/wrangler-action deploys Workers; Pages and Workers can also build directly from a Git repository using Workers Builds.
  • Official SDKs for TypeScript, Python and Go wrap the REST API with typed methods.
  • Cloudflare MCP and CLI tools for scripts and AI assistants, always using narrowly scoped tokens.

Safe-change habits

  1. Use separate tokens for each pipeline, scoped to one zone.
  2. Run plan on pull requests; apply from the main branch only.
  3. Protect critical records with lifecycle { prevent_destroy = true }.
  4. Lower DNS TTLs before a migration and restore them after.
  5. Keep an export of your zone (DNS export or Terraform state) so you can rebuild after a mistake.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which credential should an automation job use?

    Scoped tokens limit damage if leaked and can expire. The Global API Key has account-wide power and should be avoided.
  2. 2. Which JSON fields should every API client check?

    The envelope tells you if the call worked and lists error codes and messages, even for some HTTP 200 responses.
  3. 3. How should a client react to HTTP 429?

    A 429 means you hit the rate limit. Back off, honor Retry-After, and limit retries.
  4. 4. What does a Terraform plan after someone edited a record in the dashboard show?

    Terraform compares state and configuration with the real zone, so manual edits appear as proposed changes.

Summary

  • Use narrowly scoped API tokens; the REST API at /client/v4/ returns an envelope with success, errors, result and result_info.
  • Paginate with page and per_page, and retry politely on 429.
  • The Terraform provider makes Cloudflare configuration reviewable code; pin the provider version and check renamed resources between majors.
  • Plan on pull requests, protect critical resources, watch for drift and keep exports.

Next: Limits, Costs and Troubleshooting