All posts

6 min read

Cloudflare developer learning Terraform: what carries over, what's new, 30-day plan

Practical guide for Cloudflare engineers transitioning to Terraform, covering transferable skills, new concepts, pitfalls, a 30‑day roadmap, and quick FAQ.

What carries over

Cloudflare habit / conceptTerraform equivalentWhy it matters
Declarative resource definition – you describe what you want (e.g., a DNS record) and the platform enforces it.Terraform’s resource blocks (resource "cloudflare_record" "example" { … }).Both avoid imperative scripting; the engine reconciles state.
Zone‑level thinking – you always work inside a zone (domain).Terraform providers require the zone_id attribute for most Cloudflare resources.Keeps the same scoping model; you still need to fetch the zone ID (often via data "cloudflare_zones").
API token scopes – you limit tokens to specific permissions.Terraform provider configuration uses the same token (api_token = var.cloudflare_api_token).No change in security model; just pass the token as a variable.
Versioned API endpoints – you target a specific API version (v4).Terraform provider pins to a Cloudflare API version internally; you don’t specify it, but you should pin provider version in required_providers.Guarantees consistent behavior across runs.
Use of JSON/YAML for payloads – you often hand‑craft request bodies.Terraform’s HCL is a superset of JSON; you can even write resources in JSON if you prefer.You can still embed raw JSON for complex fields (json = jsonencode({...})).
Testing with curl or wrangler – quick sanity checks.Terraform has terraform plan (dry‑run) and terraform apply -target=… for focused changes.Gives you a safe preview before any mutation.
Environment variables for secrets – CF_API_TOKEN.Same env var works; additionally Terraform reads TF_VAR_* variables automatically.No new secret‑handling workflow needed.
Resource naming conventions – you use kebab‑case or snake_case for identifiers.Terraform resource names must be snake_case and unique within a module.Minor syntax shift, but the mental model stays.

What's new

Side‑by‑side example: creating a single DNS A record

Cloudflare API (curl)

curl -X POST "https://api.cloudflare.com/client/v4/zones/<ZONE_ID>/dns_records" \
     -H "Authorization: Bearer $CF_API_TOKEN" \
     -H "Content-Type: application/json" \
     --data '{
       "type": "A",
       "name": "app.example.com",
       "content": "203.0.113.42",
       "ttl": 3600,
       "proxied": false
     }'

Terraform

resource "cloudflare_record" "app_a" {
  zone_id = data.cloudflare_zones.example.id
  name    = "app"
  type    = "A"
  value   = "203.0.113.42"
  ttl     = 3600
  proxied = false
}

What changed and why

  1. State management – Terraform stores the record’s ID in its state file, enabling drift detection and safe updates. The curl approach is stateless; you must manually track IDs.
  2. Idempotence – Running terraform apply repeatedly will not create duplicate records; Terraform sees the existing resource and updates only if needed. The curl command would create a duplicate unless you first GET and compare.
  3. Dependency graph – Terraform can automatically fetch the zone ID via a data source (data.cloudflare_zones.example) and wire it into the resource. In curl you manually insert the ID.
  4. Plan preview – terraform plan shows the exact changes before they happen, reducing accidental mis‑configurations. No equivalent preview exists with raw API calls.

Other new concepts

Terraform featureCloudflare equivalent (or none)Practical impact
Modules – reusable, versioned collections of resources.No direct analogue; you may copy‑paste snippets.Encourages DRY code and easier sharing across teams.
Backend – remote state storage (e.g., Cloudflare Workers KV, S3, Terraform Cloud).Cloudflare has no built‑in state store.Enables collaboration, locking, and history.
Provisioners – run arbitrary scripts after resource creation.You’d normally use a separate CI step.Useful for edge‑case actions but should be used sparingly.
Workspace – multiple logical instances of the same configuration (e.g., dev, prod).You’d manage separate zones or API tokens.Simplifies environment segregation without code duplication.
Expressions & functions – lookup, join, cidrsubnet, etc.Cloudflare API has limited templating.Allows complex calculations inside HCL, reducing external scripting.

Common pitfalls

  1. Forgetting to run terraform init after adding a provider – the provider plugins won’t be downloaded, leading to “provider not found” errors.
  2. Hard‑coding IDs – Cloudflare IDs (zone, record) change between accounts. Use data sources or variables instead of copy‑pasting.
  3. State file leakage – committing terraform.tfstate to Git exposes API tokens and resource IDs. Use a remote backend and add .gitignore rules.
  4. Misunderstanding count vs for_each – count creates indexed resources; for_each uses a map/set key, preserving meaningful names. Pick the right one to avoid confusing plan output.
  5. Applying changes without a plan – skipping terraform plan can surprise you with bulk deletions, especially when a resource’s required attribute (e.g., zone_id) is mis‑referenced.
  6. Using the wrong provider version – newer provider releases may deprecate arguments (e.g., value vs content). Pin the version in required_providers to avoid breaking CI pipelines.
  7. Neglecting depends_on – Terraform usually infers dependencies, but when you use external data sources (e.g., a script that creates a zone) you must declare explicit dependencies to avoid race conditions.

Your 30‑day plan

Week 1 – Foundations

  1. Install Terraform (brew install terraform or appropriate package) and verify terraform version.
  2. Create a minimal project: main.tf with the Cloudflare provider block, using an environment variable for the token.
  3. Run terraform init, terraform plan, and terraform apply on a single DNS A record (the example above).
  4. Mini‑project: Build a reusable module dns_record that accepts name, type, value, and ttl and use it to create three records for app, api, and www.

Week 2 – State & Collaboration

  1. Set up a remote backend (e.g., Terraform Cloud free tier or an S3 bucket with DynamoDB lock).
  2. Migrate local state with terraform init -migrate-state.
  3. Add a second environment (staging) using workspaces: terraform workspace new staging.
  4. Mini‑project: Mirror the production DNS records into the staging workspace, using variables to switch zones. Verify that terraform plan shows only the differences.

Week 3 – Advanced Resources & Modules

  1. Explore page rules, firewall rules, and Workers scripts via Terraform resources (cloudflare_page_rule, cloudflare_firewall_rule, cloudflare_worker_script).
  2. Use for_each to manage a list of firewall rules from a variable map.
  3. Write a root module that calls sub‑modules: dns, firewall, workers.
  4. Mini‑project: Deploy a simple Cloudflare Worker that returns a JSON health check, attach it to a route, and protect the route with a firewall rule that only allows your IP range.

Week 4 – Automation & Best Practices

  1. Integrate Terraform into your CI pipeline (GitHub Actions example): terraform fmt, terraform validate, terraform plan -out=plan.out, terraform apply plan.out.
  2. Enable policy as code with Sentinel or terraform validate custom checks to enforce naming conventions.
  3. Conduct a drift detection run: terraform plan -detailed-exitcode and handle any out‑of‑band changes made via the Cloudflare dashboard.
  4. Capstone project: Refactor all previous work into a single repository with version‑pinned provider, remote backend, multiple workspaces (dev, staging, prod), and a CI pipeline that automatically promotes changes from dev → staging → prod after manual approval.

FAQ

How do I retrieve the Cloudflare zone ID without hard‑coding it?

Use a data source:

data "cloudflare_zones" "example" {
  filter {
    name = "example.com"
  }
}

Then reference data.cloudflare_zones.example.zones[0].id.

Can I manage existing Cloudflare resources with Terraform without recreating them?

Yes. Import them with terraform import cloudflare_record.my_record <ZONE_ID>/<RECORD_ID> and then add the matching resource block to your configuration.

What remote backend do you recommend for a small team?

Terraform Cloud’s free tier offers secure state storage, locking, and a simple UI—ideal for teams of up to five members.

How do I handle secrets like the API token in CI pipelines?

Store the token in the CI’s secret store (GitHub Actions Secrets, GitLab CI variables) and reference it via TF_VAR_cloudflare_api_token or the provider’s api_token variable. Terraform never writes the token to the state file.

Keep going

#cloudflare #terraform #devops #learning