Skip to content
AnswerWell geo Documentation

Research · 8 min read · Answerwell

Terraform Infrastructure as Code: Lifecycle, Structure, Import, and Troubleshooting

How to manage Cloudflare with Terraform: version control, directory layout, import, rulesets, state conflicts, and common API errors.

This page summarizes Cloudflare’s documentation on using Terraform to configure the Cloudflare global network with HashiCorp Terraform. You define infrastructure in .tf files, store changes in Git, and apply them with terraform plan and terraform apply instead of calling the Cloudflare API directly for every change.

Configure Cloudflare using HashiCorp’s “Infrastructure as Code” tool, Terraform. With Cloudflare’s Terraform provider ↗︎, you can manage the Cloudflare global network using the same familiar tools you use to automate the rest of your infrastructure. Define and store configuration in source code repositories like GitHub, track and version changes over time, and roll back when needed — all without needing to use the Cloudflare APIs.

— Cloudflare, Cloudflare Terraform provider

Terraform provider: what you can manage as code

Section titled “Terraform provider: what you can manage as code”

The Cloudflare Terraform provider covers DNS, security rules, access, Workers, and many other products. Additional configurations lists examples including WAF Managed Rules, DDoS managed rulesets, rate limiting, WAF custom rules, Transform Rules, redirects, Configuration Rules, Origin Rules, Cache Rules, Snippets, and Workers.

Cloudflare One and Zero Trust can also be managed programmatically: see API and Terraform and optional Terraform steps in Create a Zero Trust organization. Enterprise organization resources have extra authentication constraints described under Organizations for Enterprise.

For programmatic access outside Terraform, Cloudflare documents the REST API and client libraries in Interact with Cloudflare; Terraform is one option alongside the API and official SDKs.

Get started: install Terraform and avoid split management

Section titled “Get started: install Terraform and avoid split management”

Before writing resources, install the Terraform CLI using HashiCorp’s installation guide (linked from Get started).

The same principle appears in Best practices: Terraform works best when it owns the full lifecycle of each resource. If dashboard or API edits drift from state, you may need to import or recreate resources because not every resource supports in-place reconciliation.

Version Management is incompatible with Terraform for the same zone: choose Terraform or Version Management, not both.

Track configuration in Git: version control and secrets

Section titled “Track configuration in Git: version control and secrets”

After an initial apply (for example from the Terraform tutorial series), store configuration in version control for review and rollback. Track your history recommends ignoring local Terraform artifacts and sensitive variable files:

.terraform/
*.tfstate*
.terraform.lock.hcl
terraform.tfvars

Commit main.tf and .gitignore, push to a remote such as GitHub, and keep API tokens and zone IDs out of the repository (for example in terraform.tfvars, which stays local or in a secret store). Tutorial snippets in current docs often target the v5 Cloudflare provider SDK; some rule examples still note v4 — check the note on the page you copy from, such as Define a single configuration rule using Terraform.

For routine updates, run terraform plan then terraform apply, as in Add exceptions with Page Rules. Report provider bugs via the GitHub link on the Cloudflare Terraform provider overview page.

Best practices: directory structure and modules

Section titled “Best practices: directory structure and modules”

Best practices recommends layout by account, zone, and product so ownership and blast radius stay small.

Cloudflare recommends using a directory structure that relies on a combination of accounts, zones, and products for isolating changes. This setup lets you have fine-grained owners and scoped Terraform operations to a specific product in a zone.

— Cloudflare, Best practices

A typical pattern nests provider.tf, <subject>.tf, and vars.tf per component (for example dns/, page_rules/, account-level users/). For large Rulesets deployments, partition further by phase (WAF, redirects, origin rules).

Cloudflare advises using Terraform modules sparingly. Shared modules that change internally can recreate resources or leave them out of sync, and debugging must account for module logic outside Terraform core and the Cloudflare provider. The same caution applies to dynamic blocks in HCL when they introduce hard-to-reproduce logic bugs.

It is acceptable to manage some resources in Terraform and others elsewhere, but never the same resource through two channels (Best practices).

For existing dashboard configuration, Cloudflare recommends cf-terraforming to generate config and import state. Advanced topics also cover provider customization and storing state in a remote R2 backend with terraform init -reconfigure.

Import existing Cloudflare resources into Terraform

Section titled “Import existing Cloudflare resources into Terraform”

Terraform only manages resources it created or that you explicitly imported (Import Cloudflare resources). It needs:

  • A .tf configuration defining the resource
  • State (default terraform.tfstate or a remote backend) mapping resource names to Cloudflare IDs

If you configured Cloudflare through other means, for example, by logging in to the Cloudflare dashboard or making curl calls to api.cloudflare.com, Terraform does not yet have these resource IDs in the state file. To manage this preexisting configuration, you will need to first reproduce the configuration in your config file and then import resources individually by providing their IDs and resource names.

— Cloudflare, Import Cloudflare resources

cf-terraforming fetches resources of a chosen type for an account or zone and supports generate and import workflows. Install via Homebrew (brew tap cloudflare/cloudflare and brew install cloudflare/cloudflare/cf-terraforming) or from the tool’s GitHub releases (see Installation). You pass email, API token, account or zone scope, and the resource types to export; supported types are listed in the provider README linked from that page.

For rulesets (WAF, rate limiting, Transform Rules, DDoS, and similar), Terraform assumes full control. If rulesets already exist, either import with cf-terraforming or delete existing root/zone rulesets and redefine them in Terraform — see WAF custom rules configuration using Terraform, Rate limiting rules configuration using Terraform, and DDoS managed rulesets configuration using Terraform.

Rulesets in Terraform: stable rule IDs with ref

Section titled “Rulesets in Terraform: stable rule IDs with ref”

Modern WAF and configuration rules use cloudflare_ruleset. Without care, edits can replace rules and change IDs, which breaks automation that keys off rule IDs (Rule IDs change when I modify a ruleset).

To keep existing rule IDs when making changes to a ruleset through Terraform, add a ref field to each rule.

— Cloudflare, Rule IDs change when I modify a ruleset

The ref field is a unique per-rule external identifier. When it matches an existing rule, the provider updates in place instead of delete-and-create. Example pattern from Define a single configuration rule using Terraform:

rules {
ref = "disable_obfuscation_bic"
description = "Disable email obfuscation and BIC for API requests"
expression = "(http.request.uri.path matches \"^/api/\")"
action = "set_config"
action_parameters {
email_obfuscation = false
bic = false
}
}

After import via cf-terraforming, ref values often equal the existing rule ID. If you author rules by hand, add ref before the first production apply. Changing ref later creates a new rule.

Legacy WAF package resources are replaced by cloudflare_ruleset for managed rules (WAF managed rules upgrade); follow WAF Managed Rules configuration using Terraform for current examples.

Troubleshooting: authentication and zone data sources

Section titled “Troubleshooting: authentication and zone data sources”

A common DNS error is HTTP 403 with authentication error 10000 (403 Authentication error when creating DNS records). Cloudflare documents a frequent cause: incorrect syntax when reading zone IDs from data.cloudflare_zones — use the indexed zone, not a non-existent top-level id:

# Wrong
zone_id = data.cloudflare_zones.example_com.id
# Correct
zone_id = data.cloudflare_zones.example_com.zones[0].id

Also verify the API token has DNS write permission for the target zone. Product-specific guides (for example Configure Cloud Connector rules using Terraform) list minimum token scopes such as Zone > Cloud Connector > Write.

Optional provider settings and environment variables are covered in Provider customization. Organization management may require a Global API key plus account email rather than a user API token for full lifecycle support (Organizations for Enterprise).

More entries are listed on Troubleshooting.

How-to guides and product-specific Terraform docs

Section titled “How-to guides and product-specific Terraform docs”

Common setup tasks live under How-to guides, including Create a partial zone using Terraform (subdomain on Cloudflare while the parent zone stays elsewhere — partial zones cannot sit in the same account as the parent’s full zone) and Create a subdomain zone using Terraform.

Examples for individual features link back to the main Terraform documentation and the provider reference (for instance Configure Bulk Redirects using Terraform, VPC Services with Terraform requiring provider v5.13.0+, and Internal DNS with type = "internal" on cloudflare_zone).

Provider release notes appear on the Terraform changelog product page and individual version posts (for example Terraform v5.17.0), which point to migration guides and stabilized resource lists when upgrading.

Mistake Why it hurts What docs recommend
Editing the same resource in the dashboard and Terraform State drift; surprise destroys or recreates Single channel per resource; see Get started and Best practices
Applying rulesets without import or cleanup Terraform fights existing rulesets Import or delete then define; see WAF custom rules configuration using Terraform
Omitting ref on cloudflare_ruleset rules Rule IDs change on every edit Add stable ref; see Rule IDs change when I modify a ruleset
Wrong data.cloudflare_zones attribute 403 on DNS create Use zones[0].id; see 403 Authentication error when creating DNS records
Terraform + Version Management on one zone Unsupported combination Pick one; see Version Management troubleshooting
Committing terraform.tfvars or state files Leaked tokens and infrastructure details .gitignore per Track your history
  1. Run terraform plan in each Terraform root module and confirm changes match what you expect before any apply (Add exceptions with Page Rules).
  2. After apply, use the Cloudflare dashboard or Make API calls (https://api.cloudflare.com/client/v4/) to verify resources (DNS records, rulesets, Access apps) match your .tf definitions.
  3. For rulesets, note rule IDs in the API or UI, change a non-ref field in Terraform, and confirm IDs stay stable when each rule has a ref (Rule IDs change when I modify a ruleset).
  4. Confirm secrets are not in Git: terraform.tfvars, *.tfstate*, and .terraform/ should be absent from the remote per Track your history.
  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about, and we will follow up.