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 / concept | Terraform equivalent | Why 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
- 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.
- Idempotence – Running
terraform applyrepeatedly will not create duplicate records; Terraform sees the existing resource and updates only if needed. The curl command would create a duplicate unless you firstGETand compare. - Dependency graph – Terraform can automatically fetch the zone ID via a
datasource (data.cloudflare_zones.example) and wire it into the resource. In curl you manually insert the ID. - Plan preview –
terraform planshows the exact changes before they happen, reducing accidental mis‑configurations. No equivalent preview exists with raw API calls.
Other new concepts
| Terraform feature | Cloudflare 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
- Forgetting to run
terraform initafter adding a provider – the provider plugins won’t be downloaded, leading to “provider not found” errors. - Hard‑coding IDs – Cloudflare IDs (zone, record) change between accounts. Use
datasources or variables instead of copy‑pasting. - State file leakage – committing
terraform.tfstateto Git exposes API tokens and resource IDs. Use a remote backend and add.gitignorerules. - Misunderstanding
countvsfor_each–countcreates indexed resources;for_eachuses a map/set key, preserving meaningful names. Pick the right one to avoid confusing plan output. - Applying changes without a plan – skipping
terraform plancan surprise you with bulk deletions, especially when a resource’s required attribute (e.g.,zone_id) is mis‑referenced. - Using the wrong provider version – newer provider releases may deprecate arguments (e.g.,
valuevscontent). Pin the version inrequired_providersto avoid breaking CI pipelines. - 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
- Install Terraform (
brew install terraformor appropriate package) and verifyterraform version. - Create a minimal project:
main.tfwith the Cloudflare provider block, using an environment variable for the token. - Run
terraform init,terraform plan, andterraform applyon a single DNS A record (the example above). - Mini‑project: Build a reusable module
dns_recordthat acceptsname,type,value, andttland use it to create three records forapp,api, andwww.
Week 2 – State & Collaboration
- Set up a remote backend (e.g., Terraform Cloud free tier or an S3 bucket with DynamoDB lock).
- Migrate local state with
terraform init -migrate-state. - Add a second environment (staging) using workspaces:
terraform workspace new staging. - Mini‑project: Mirror the production DNS records into the staging workspace, using variables to switch zones. Verify that
terraform planshows only the differences.
Week 3 – Advanced Resources & Modules
- Explore page rules, firewall rules, and Workers scripts via Terraform resources (
cloudflare_page_rule,cloudflare_firewall_rule,cloudflare_worker_script). - Use
for_eachto manage a list of firewall rules from a variable map. - Write a root module that calls sub‑modules:
dns,firewall,workers. - 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
- Integrate Terraform into your CI pipeline (GitHub Actions example):
terraform fmt,terraform validate,terraform plan -out=plan.out,terraform apply plan.out. - Enable policy as code with Sentinel or
terraform validatecustom checks to enforce naming conventions. - Conduct a drift detection run:
terraform plan -detailed-exitcodeand handle any out‑of‑band changes made via the Cloudflare dashboard. - 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