Discuss your project

Blog

Moving a hand-built Cloudflare account into Terraform without downtime

Mher Poghosyan · 29 November 2026 · 8 min read

Most Cloudflare accounts start in the dashboard. It works, but nobody can say why a setting has its value, and every change is a click with no review and no history.

Our own account was like that: two zones with DNS records, several Cloudflare Tunnels to a server running n8n, Access applications and a policy in front of them, four response header rules, HSTS, SSL and cache settings. Some of it was set by hand, some by a small Python script. We moved all of it into Terraform with Terragrunt and the Cloudflare provider v5. Nothing was recreated and no site went down. Here is the order we followed and the traps we hit.

The rule: no changes until the plan is empty

An import is not the moment to improve anything. While importing, the only acceptable plan is:

Plan: N to import, 0 to add, 0 to change, 0 to destroy.

After the apply, the next plan must say No changes. Your infrastructure matches the configuration. Every ~ or + before that means the code does not yet describe reality: fix the code, not Cloudflare. Improvements come afterwards, as small separate changes with their own plans.

Before the first import: state and one token

State lives in Cloudflare R2. Terraform’s S3 backend works with R2 and, since Terraform 1.10, locks state with a lock file in the same bucket (use_lockfile). We generate the backend with Terragrunt’s generate block rather than remote_state, so Terragrunt does not try to create or configure the bucket:

generate "backend" {
  path      = "backend.tf"
  if_exists = "overwrite_terragrunt"
  contents  = <<-EOF
    terraform {
      backend "s3" {
        bucket       = "<state-bucket>"
        key          = "${path_relative_to_include()}/terraform.tfstate"
        region       = "auto"
        endpoints    = { s3 = "https://<account-id>.eu.r2.cloudflarestorage.com" }
        use_lockfile = true

        use_path_style              = true
        skip_credentials_validation = true
        skip_region_validation      = true
        skip_requesting_account_id  = true
        skip_metadata_api_check     = true
        skip_s3_checksum            = true
      }
    }
  EOF
}

The state bucket itself is created by Terraform: first with local state, then terragrunt init -migrate-state moves that state into the bucket it just created. Terraform also creates the R2 token for state, scoped to that one bucket.

One API token per provider. Terraform gets a single account-owned Cloudflare token with only the permissions it uses:

When we later added Cloudflare Pages and a Worker, we extended this token instead of creating a second one: one place to rotate, one list of permissions to review. It is stored encrypted with SOPS and reaches Terraform only as the CLOUDFLARE_API_TOKEN environment variable.

Describe what exists, then import it

Every zone has the same shape, so we wrote one module, cloudflare-site, and one Terragrunt stack per zone with its inputs: records, tunnels and their hostnames, the Access policy, header rules, settings.

Then import blocks, one per existing object. They are only allowed in the root module; with Terragrunt the stack is the root module, so each stack generates its own file:

generate "imports" {
  path      = "imports.tf"
  if_exists = "overwrite_terragrunt"
  contents  = <<-EOF
    import {
      to = cloudflare_zone.this
      id = "<zone-id>"
    }
    import {
      to = cloudflare_dns_record.this["spf"]
      id = "<zone-id>/<record-id>"
    }
    import {
      to = cloudflare_zero_trust_access_application.this["n8n.example.com"]
      id = "accounts/<account-id>/<app-id>"
    }
  EOF
}

ID formats differ between resources: Access applications need the accounts/ prefix, Access policies and tunnels do not, rulesets use zones/<zone-id>/<ruleset-id>. Check each resource’s import section in the provider docs. The IDs themselves come from the API, for example GET /zones/<zone-id>/dns_records for records.

Zone settings are different: they always exist and cannot be created, only adopted. The module imports them itself whenever the stack passes the ID of an existing zone:

import {
  for_each = var.zone_id == null ? toset([]) : toset(keys(var.settings))
  to       = cloudflare_zone_setting.this[each.key]
  id       = "${var.zone_id}/${each.key}"
}

For kubmeta.com alone that was 23 import blocks, plus the zone settings.

Read the plan until it is empty

The first plans were not empty. Each difference taught us something about the provider:

  # Cloudflare's defaults, written out: without them the plan shows false -> null
  auto_redirect_to_identity = false
  enable_binding_cookie     = false
  options_preflight_bypass  = false

Rulesets: adopt them, never recreate them

The four header rules (X-Frame-Options, Permissions-Policy, Content-Security-Policy, Referrer-Policy) were created in the dashboard. Cloudflare keeps them in the zone’s entry-point ruleset for the http_response_headers_transform phase, and a zone has only one entry point per phase. Terraform cannot create a second one next to it, and deleting the dashboard ruleset to make room would leave the site without those headers until the apply finishes.

So the ruleset is imported, and each rule keeps the ID it already has as its ref, in the same order as in the dashboard:

existing_rulesets = {
  http_response_headers_transform = "<ruleset-id>"
}
response_headers = [
  { ref = "<rule-id>", name = "X-Frame-Options", header = "X-Frame-Options", value = "SAMEORIGIN" },
  { ref = "<rule-id>", name = "Referrer-Policy", header = "Referrer-Policy", value = "same-origin" },
]

Rule IDs come from GET /zones/<zone-id>/rulesets/<ruleset-id>. These rules mattered more than we expected: one of them was silently replacing our website’s CSP, a story for a separate article.

Protect what must never be recreated

A zone and a tunnel must never be recreated. A new tunnel gets a new ID and a new token: every cloudflared running with the old token disconnects, and every CNAME pointing to <old-id>.cfargotunnel.com breaks. Both carry prevent_destroy:

resource "cloudflare_zero_trust_tunnel_cloudflared" "this" {
  for_each   = var.tunnels
  account_id = var.account_id
  name       = each.key
  config_src = "cloudflare"

  lifecycle {
    prevent_destroy = true # a new tunnel means a new ID and token
  }
}

A -/+ (replace) on anything in the plan is a reason to stop and read, not to type yes.

Order matters once you start changing things. When we switched the zones to Full (strict), two hostnames still pointed at an old server with an expired self-signed certificate. They got temporary SSL exceptions as configuration rules, and the SSL setting depends_on those rules and the tunnel records, so it is applied last and no host returns 526 halfway through the apply.

Refactor with moved blocks

On 29 November we moved kubmeta.com and www from a placeholder page served through our tunnel to Cloudflare Pages. In the module, tunnel hostnames and Pages domains are different resources: cloudflare_dns_record.tunnel[...] and cloudflare_dns_record.pages[...]. Without help, Terraform deletes one record and creates another, with no ordering between the two: the create can fail because the old CNAME still exists, or the site is left without a record for a moment.

A moved block tells Terraform it is the same record under a new address:

moved {
  from = cloudflare_dns_record.tunnel["kubmeta.com"]
  to   = cloudflare_dns_record.pages["kubmeta.com"]
}
moved {
  from = cloudflare_dns_record.tunnel["www.kubmeta.com"]
  to   = cloudflare_dns_record.pages["www.kubmeta.com"]
}

The plan then shows an in-place update of the record’s target, not a delete and a create:

  # cloudflare_dns_record.pages["kubmeta.com"] will be updated in-place
  # (moved from cloudflare_dns_record.tunnel["kubmeta.com"])
  ~ resource "cloudflare_dns_record" "pages" {
      ~ comment = "Cloudflare Tunnel" -> "Cloudflare Pages"
      ~ content = "<tunnel-id>.cfargotunnel.com" -> "<project>.pages.dev"
        name    = "kubmeta.com"
        # (unchanged attributes hidden)
    }

Moves that belong to one zone live in that stack’s generated file, next to the provider block. Moves that apply to every zone go into the module. When the shared Access policy became optional (count), one moved block in the module, from ...access_policy.owners to ...access_policy.owners[0], covered every stack.

Records that other services create

On 29 November we verified kubmeta.com in Google Search Console. It offers to do this through Cloudflare: you approve access, and it writes a TXT verification record into the zone through the API. Terraform knew nothing about it.

Nothing breaks at that moment: Terraform ignores what it does not manage. The trouble comes later. Someone adds the record to the code, and a plain apply tries to create a duplicate, which the API rejects. Or someone cleans up the zone to match the code, and the domain loses its verification.

We added the record to the config with a clear comment and imported it:

"google-search-console" = {
  type    = "TXT"
  name    = "kubmeta.com"
  content = "\"google-site-verification=<token>\""
  ttl     = 3600
  comment = "Google Search Console: domain verification (do not delete)"
}
cd live/kubmeta/cloudflare
terragrunt import 'cloudflare_dns_record.this["google-search-console"]' '<zone-id>/<record-id>'
terragrunt plan

A plan never shows records Terraform does not manage. To find them, compare the API’s list with the state from time to time:

terragrunt show -json \
  | jq -r '.values.root_module.resources[] | select(.type == "cloudflare_dns_record") | .values.id' \
  | sort > managed.txt
curl -s -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records?per_page=100" \
  | jq -r '.result[].id' | sort > live.txt
comm -13 managed.txt live.txt   # records that exist only in Cloudflare

After the import

Once applied, import blocks do nothing for objects already in state. We deleted them anyway: they clutter the code and carry IDs nobody needs to read. The commit that removed them says it plainly: plan for all stacks, no changes.

Checklist

The import is the boring part, and that is the point: the account looks exactly the same afterwards. The benefit comes with the next change: a plan, a review and a commit instead of a click. If your Cloudflare setup has grown by hand and you want it in code without a maintenance window, tell us about it.

#terraform#cloudflare#devops#iac