Back to Terraform

DNS as Code: Zones, Proxied Records, Delegation and DNSSEC

November 6, 2026 Wasil Zafar 35 min read

Manage DNS ownership with stable record addresses and verify changes at authoritative and recursive resolvers

Table of Contents

  1. Separate Registrar Delegation from Zone Configuration
  2. Use Cloudflare DNS Record Schemas for the Selected Release
  3. Keep Record Identity Stable as the Zone Grows
  4. Coordinate DNSSEC and DS Records with the Registrar
  5. Import an Existing Record and Prove the Result

Separate Registrar Delegation from Zone Configuration

A zone can look finished while the internet still asks someone else. The dashboard says Active, terraform apply reported success, and a resolver on the other side of the world still returns the old provider's address. Nothing in state is wrong. The change stopped at a boundary Terraform does not own.

Three layers decide who answers a query, and only one of them is the zone. Registration is the contract with the registrar: who owns the name, when it expires, which contacts receive notices. Delegation is a single NS record set published by the parent zone — the TLD registry, in the common case — that tells resolvers which servers to ask. Authority is the zone itself: the records those servers answer with. A mistake in any layer produces the same symptom, which is why the layers are worth separating before touching Terraform.

The zone object is the part Cloudflare gives you an API for. A cloudflare_zone resource creates that object and returns the nameservers Cloudflare assigned to it. Those nameservers are a computed result, not an input. Terraform can read them and print them; it cannot install them at your registrar.

Pending is a real serving state, not a waiting room. Cloudflare answers queries on the assigned nameserver addresses while a zone is pending, but proxying is unavailable, and a Free-plan zone that never activates is deleted after 28 days. Activation requires the registrar to list exactly the assigned nameservers, with no extras from another DNS provider unless multi-provider DNS is enabled.

LayerWho performs the changeWhere the record livesWhat Terraform can do
RegistrationRegistrar accountRegistry registration databaseUsually nothing through this provider
DelegationRegistrar or parent-zone ownerNS RRset at the parentRead name_servers; compare, not set
AuthorityCloudflareThe zone's record setCreate, update, delete, import
DNSSEC chainCloudflare plus registrarDNSKEY in the zone, DS at the parentSign the zone; read the DS to publish

Full setup is the default because it moves authority. With type = "full", Cloudflare becomes the authoritative server for the whole zone, and the registrar's NS RRset is the switch that makes it real. Until that switch is thrown, every record you write is visible only to Cloudflare and to anyone who queries the assigned nameservers directly.

Partial setup keeps your DNS provider and borrows the proxy. A partial zone needs a Business or Enterprise plan, is unavailable for domains registered through Cloudflare Registrar, and never changes the registrar's nameservers. Instead, a verification TXT record proves ownership and must stay in place, while each hostname you want proxied becomes a CNAME to cdn.cloudflare.net. The apex is the awkward case, because a CNAME cannot coexist with the apex's other records unless the authoritative provider flattens it.

Secondary and internal cover the remaining cases. A secondary zone receives its records from a primary provider through zone transfer and allows both providers' nameservers at the parent, which is how multi-provider DNS stays available. An internal zone has no public delegation at all; it exists for private resolution rather than for the internet.

Vanity nameservers change the label, not the rule. A Business or Enterprise zone can present custom nameserver hostnames, and those names still have to appear in the parent's NS RRset exactly as Cloudflare reports them. The same applies to a subdomain setup, where a parent zone delegates sub.example.com to a child zone in another account: the parent holds one NS record set, and the child holds the records. Neither arrangement lets Terraform write the delegation from the child side.

Figure 1 draws the two control planes and the branch that skips delegation entirely.

Separate Registrar Delegation from Zone Configuration
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','signalColor':'#5a6e82','noteBkgColor':'#c4873b','noteTextColor':'#132440','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    R["Registrar holds the registration"] --> P["Parent zone publishes the NS RRset"]
    P -->|"referral"| N["Cloudflare assigned nameservers"]
    N --> S{"Zone status"}
    S -->|"pending"| Q["Answers on assigned IPs only, proxy disabled"]
    S -->|"active"| A["Authoritative records are served"]
    A --> X{"Record proxied?"}
    X -->|"yes"| E["Anycast edge address, TTL 300"]
    X -->|"no"| O["Origin value, your TTL"]
    R -.->|"no NS change"| V["Partial zone: verification TXT"]
    V --> C["Hostname CNAME to cdn.cloudflare.net"]
    A --> D["NS record at a subdomain"]
    D --> Z["Another provider becomes authoritative"]
    classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
    classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
    classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
    classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
    classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
    class R,P,S,X primary;
    class N,A,D,O,E secondary;
    class Q danger;
    class V,C,Z warn;

Delegation repeats inside a zone. An NS record at a subdomain moves authority for that name and everything below it, which is how one team hands sub.example.com to a different provider or a different Cloudflare account. The records already stored below that name do not disappear; they stop being served, and Cloudflare marks them as shadowed. An address record for a nameserver that lives inside the delegated zone is glue, and glue is the one exception that must still resolve.

Figure 2 shows where the Terraform boundary actually falls: the zone on the right, the delegation on the left, and the one value that crosses between them.

Registrar, parent zone and Cloudflare zone as three separate layers The registrar holds the registration. The parent zone publishes the NS RRset that delegates the domain to Cloudflare's assigned nameservers. Terraform writes records and DNSSEC signing inside the Cloudflare zone, and can only read the assigned nameservers that the parent must publish. Three layers, two control planes Registrar Registration record owner, expiry, contacts set once, rarely touched separate login and API Parent zone NS RRset for the domain ns1.example.net ns2.example.net the actual delegation Cloudflare zone Authoritative records A, AAAA, CNAME, MX, TXT proxied or DNS only DNSSEC signing Terraform writes here Terraform reads, but cannot publish The zone resource returns name_servers after creation. Those names must be copied to the registrar by a person, a registrar API, or a separate Terraform provider. No amount of apply changes the parent zone. assigned NS A pending zone still answers on the assigned nameservers, but it does not proxy traffic. An active zone with the wrong NS RRset at the parent is invisible to recursive resolvers. Registration, delegation and authority fail in different places and need different evidence.

The only honest proof of delegation is a query at the parent. Ask the parent for the NS record set and compare it with the nameservers Terraform reports. A match explains an active zone; a mismatch explains a zone that resolves only when you query the assigned server directly. This is also the first check when a zone has been pending for longer than a coffee break.

Trace the referral chain when the NS answer is ambiguous. A trace walks from the root through the parent and shows which server returned the delegation, while a cached answer from a local resolver skips that path entirely. If the trace reaches Cloudflare and an ordinary query does not, the zone is healthy and the cache is old.

Terraform proves the zone; only the registrar proves the delegation. Keep those claims separate in your runbook, and a surprising DNS result stops being mysterious. The next section moves inside the zone, where Terraform does have full authority.

Use Cloudflare DNS Record Schemas for the Selected Release

Provider 5.x rewrote the record resource instead of extending it. Two v4 arguments, value and allow_overwrite, are gone, and their replacements change the shape of a record block. Code copied from a 4.x example will fail before it reaches the API.

The TTL moved from optional to required. In 5.x a record without a TTL is invalid configuration, even though the API has a sensible default. That single change is responsible for a large share of failed upgrades, because the omission is invisible until the plan runs.

Four arguments are required: the zone, the record name, the type and the TTL. Everything else is optional or computed, and knowing which bucket a field belongs to prevents most drift.

ArgumentStatusMeaningDetail that bites
zone_idRequiredZone identifierChanging it replaces the resource
nameRequiredRecord owner@ means the apex; use one form consistently
typeRequiredRecord type21 values, case-insensitive
ttlRequiredCache lifetime1 means automatic; 60–86400 otherwise
contentOptionalThe record valueConflicts with data
dataOptionalStructured fieldsUsed by CAA, SRV, SVCB, TLSA and similar
priorityOptionalMX preferenceLower is preferred; unrelated types ignore it
proxiedOptionalOrange cloudDefaults to false when omitted
comment, tagsOptionalMetadataNo effect on answers
settingsOptionalProxy-related switchesOnly affects proxied or flattening cases

The type list is wider than the six records most teams use. A, AAAA, CNAME, MX, NS, TXT, CAA, CERT, DNSKEY, DS, HTTPS, LOC, NAPTR, OPENPGPKEY, PTR, SMIMEA, SRV, SSHFP, SVCB, TLSA and URI are all accepted. The schema is generated from the API, so a type that is missing from your provider version is a version problem, not a permissions problem.

Content and data are two ways to say the same thing, and they are mutually exclusive. Simple records — address, name, text — use the first. Structured records use the second: a CAA record needs flags, tag and value; an SRV record needs priority, weight, port and target. MX is the awkward middle case, because the mail host is a simple value while the preference sits beside it in its own argument.

TTL 1 means automatic, and a proxied record must use it. The provider rejects the combination of an orange cloud and a fixed TTL with an explicit error instead of quietly overriding your number. That is deliberate: the edge controls the answer's lifetime, and the effective TTL for a proxied record is 300 seconds.

Proxy eligibility follows the record type, not the plan. Only A, AAAA and CNAME can be proxied, because only those answers describe an address a client can connect to. The computed proxiable field reports what the API will accept for the record you wrote; asking a TXT record to be orange-clouded is a category error, not a feature request.

An omitted proxied argument is not neutral. In 5.x the field is optional with a default of false. Adopt an existing orange-cloud record with a block that omits it, and the first plan will propose turning the proxy off. That is a traffic change disguised as a formatting preference.

The name is written once and then kept in one form. The apex can be @ or the zone name; a subdomain can be a label or a fully qualified name; internationalised names must be Punycode. The provider saves the zone suffix in private state so a refresh that returns the full name is not reported as drift, but mixing forms inside one configuration makes review harder than it needs to be.

Computed values are evidence, not configuration. The record ID, proxiable, creation and modification timestamps, and the API's meta block are returned by Cloudflare. Putting any of them in the configuration creates a value that can never be satisfied on the next plan.

Three optional fields are easier to overuse than to need. The settings block controls CNAME flattening and whether a proxied name publishes only IPv4 or only IPv6 answers; flattening is unavailable on a proxied record because the proxy already flattens, and the IP-family switches change generated answers rather than origin reachability. Private routing is for private-network origins and should not be switched on to see what happens. Comments and tags are metadata that never reach a resolver, which makes them safe for ownership notes and unsafe as a substitute for documentation.

A small record set shows the shape without hiding the rules. The example pins the CLI and the provider, keeps the apex address records proxied, and leaves mail grey on purpose. The addresses come from the documentation ranges, so replace them before applying.

terraform {
  required_version = "1.17.1"

  required_providers {
    cloudflare = {
      source  = "cloudflare/cloudflare"
      version = "= 5.28.1"
    }
  }
}

variable "zone_id" {
  type = string
}

resource "cloudflare_dns_record" "apex_a" {
  zone_id = var.zone_id
  name    = "@"
  type    = "A"
  content = "192.0.2.10"
  ttl     = 1
  proxied = true
  comment = "apex address, managed by terraform"
}

resource "cloudflare_dns_record" "www" {
  zone_id = var.zone_id
  name    = "www.example.com"
  type    = "CNAME"
  content = "example.com"
  ttl     = 1
  proxied = true
}

resource "cloudflare_dns_record" "mail" {
  zone_id = var.zone_id
  name    = "mail.example.com"
  type    = "A"
  content = "192.0.2.20"
  ttl     = 300
  proxied = false
}

resource "cloudflare_dns_record" "mx" {
  zone_id  = var.zone_id
  name     = "@"
  type     = "MX"
  content  = "mail.example.com"
  priority = 10
  ttl      = 300
  proxied  = false
}

resource "cloudflare_dns_record" "caa" {
  zone_id = var.zone_id
  name    = "@"
  type    = "CAA"
  ttl     = 300

  data = {
    flags = 0
    tag   = "issue"
    value = "letsencrypt.org"
  }
}

Read the plan for the fields you did not write. Defaults, computed values and the provider's normalisation all appear there before anything is sent to Cloudflare. A plan that only reports the record you edited is the shape you want; a plan that also rewrites a neighbour means the two blocks disagree about the same owner name.

Figure 3 follows one record from configuration to served answer, with the rejection branches that account for most failed applies.

Use Cloudflare DNS Record Schemas for the Selected Release
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','signalColor':'#5a6e82','noteBkgColor':'#c4873b','noteTextColor':'#132440','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    H["HCL block: zone, name, type, ttl"] --> T{"Which type?"}
    T -->|"A, AAAA, CNAME"| P{"proxied = true?"}
    T -->|"MX, TXT, NS"| S["content plus optional priority"]
    T -->|"CAA, SRV, SVCB"| D["data map, proxied false"]
    P -->|"yes"| L{"ttl = 1?"}
    L -->|"no"| E["Rejected: proxied requires ttl 1"]
    L -->|"yes"| K{"Owner already has other data?"}
    P -->|"no"| K
    S --> K
    D --> K
    K -->|"CNAME beside A or AAAA"| X["Rejected: CNAME must be alone"]
    K -->|"unique owner"| A["API writes the record"]
    A --> C["Computed: id, proxiable, timestamps"]
    C --> F["Answer served with the record's TTL"]
    classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
    classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
    classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
    classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
    classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
    class H,T,K primary;
    class S,D,A,C,F secondary;
    class E,X danger;
    class P,L warn;

The schema is a contract, and the contract changes between majors. Reading the current resource documentation is not diligence for its own sake; it is the difference between a plan that describes your intent and a plan that describes a 4.x memory. With the fields settled, the next problem is not what a record says but which Terraform address owns it.

Keep Record Identity Stable as the Zone Grows

A record has three identities, and they move independently. The Terraform address is the label you type in a plan, such as a resource name plus a key. The Cloudflare record ID is the opaque identifier the API uses. The DNS identity is the triple of owner name, type and value that a resolver actually sees. Confusing them is how a routine edit becomes a delete-and-recreate.

The record ID is what Terraform holds in state. Import binds a zone and a record ID to an address; after that, edits to the name, type or content are patched onto the same record, and the ID survives. Only a change of zone_id forces replacement. A record deleted in the dashboard is different: the refresh drops it from state with a warning, and the next apply creates a new record with a new ID.

State is not an inventory of the zone. It contains only the records you have chosen to manage, which is why terraform state list is a poor answer to "what is in DNS". Before a large adoption, list the zone through the API, group the records by owner and type, and decide which ones Terraform should own. The ones left out are not broken; they simply have a different owner.

Renaming a Terraform address is a state move, not a DNS change. A moved block tells Terraform that the old address and the new one are the same object, so the plan is empty and the record is untouched. Without it, the plan destroys one record and creates another, which for an apex or mail record is an outage measured in TTLs.

Use a map keyed by purpose, not a list keyed by position. A for_each over a map of objects gives every record a stable key, so adding or removing one entry does not renumber its neighbours. The value inside an entry can change in place; the key is what fixes the address.

locals {
  web_records = {
    apex-v4 = {
      name    = "@"
      type    = "A"
      content = "192.0.2.10"
    }
    apex-v6 = {
      name    = "@"
      type    = "AAAA"
      content = "2001:db8::10"
    }
    www = {
      name    = "www.example.com"
      type    = "CNAME"
      content = "example.com"
    }
  }
}

resource "cloudflare_dns_record" "web" {
  for_each = local.web_records

  zone_id = var.zone_id
  name    = each.value.name
  type    = each.value.type
  content = each.value.content
  ttl     = 1
  proxied = true
}
PatternStable whenBreaks whenGood fit
Separate resource blocksAlways, but verboseYou rename the addressA handful of long-lived records
for_each over a key-to-object mapValues change in placeA key is renamedMost zones
for_each over a set of valuesThe value set is fixedAn address rotatesEphemeral pools you truly replace
count over a listThe list order never changesAnything is insertedAlmost nothing in DNS

Multi-value records need one address per value, not one address with a list. Two A records at the same owner are two API objects, so they are two Terraform instances. Key them by role — apex-v4-primary, apex-v4-secondary — and a changed address becomes an in-place update. Key them by the address itself and every rotation destroys and recreates the record, which is correct only if you want the gap.

Replacing a value and replacing a key are different operations. Editing content sends a patch and keeps the record ID. Editing the key changes the Terraform address, so Terraform plans a destroy and a create unless a moved block bridges the two. Review the plan for the word "replace" before you approve either.

Validation belongs in the variable, not in a wiki page. A malformed address fails at plan time, when the fix is cheap, instead of at apply time, when half the zone has already changed.

variable "origin_ipv4" {
  type = string

  validation {
    condition     = can(cidrhost("${var.origin_ipv4}/32", 0))
    error_message = "origin_ipv4 must be a single IPv4 address."
  }
}

Some combinations are invalid before the API sees them. A CNAME cannot share an owner with an A, AAAA or another CNAME. An apex CNAME is forbidden unless the provider flattens it. A proxied MX is not a stricter setup but a broken one. A missing MX priority produces a record the API may reject or store with an unintended preference.

CombinationWhy it failsCorrect move
CNAME beside an A or AAAAThe owner must have one answer shapeUse a CNAME alone, or address records alone
Apex CNAMEThe apex already carries NS and SOALet Cloudflare flatten it, or use A and AAAA
proxied = true on MX or TXTOnly address records have a proxy pathSet it to false and fix the TTL
Proxied record with a fixed TTLThe edge controls the answer lifetimeUse ttl = 1
Two blocks for one owner and typeLast apply wins, plan never convergesOne block per record, or one for_each

Protect the records whose loss is an outage. A prevent_destroy lifecycle on the apex address and the mail host turns an accidental removal into a failed plan. If you need to stop managing a record without deleting it, remove it from state rather than deleting the resource; the record stays in Cloudflare and Terraform forgets it.

Do not silence drift with ignore_changes. Ignoring content because a dashboard edit keeps reappearing makes the configuration a lie: the plan stays clean while the served answer differs from the file. Either own the record and let the plan correct it, or take it out of state and document who does own it.

Cloudflare creates records you did not write. Email Routing adds MX and TXT records, Workers custom domains add CNAMEs, and Access applications can add verification records. Importing all of them into one root looks tidy until the feature rotates a value and your apply fights it. Adopt a record only when you intend to own its lifecycle.

A zone grows by adding keys, not by editing a monolith. When every record has a purpose-shaped address, adding the twentieth record is the same operation as adding the first, and removing one is a one-line diff. That stability is also what makes an import reviewable, which is the subject of the final section.

Coordinate DNSSEC and DS Records with the Registrar

DNSSEC has two halves, and they live in different accounts. Signing happens inside the zone: Cloudflare publishes keys and attaches signatures to answers. Delegation happens at the parent: a DS record tells validators which key to expect. Either half alone is incomplete, and enabling one without the other produces a very specific kind of confusion.

The resource signs the zone; it does not publish the DS. A cloudflare_zone_dnssec resource takes a zone and a desired status, and returns the material a registrar needs. The DS fields are computed, which is exactly right: you do not invent a digest, you read the one Cloudflare generated.

FieldStatusWhat it tells you
zone_idRequiredThe zone to sign
statusOptionalactive signs; disabled withdraws trust
dnssec_presignedOptionalTransfer in an externally signed zone
dnssec_use_nsec3OptionalUse NSEC3 instead of NSEC
dnssec_multi_signerOptionalLet more than one provider sign
dsComputedThe full DS record for the registrar
key_tag, algorithmComputedThe key identifier and algorithm number
digest, digest_typeComputedThe hash and its type
public_key, flags, key_typeComputedThe DNSKEY material behind the DS

A minimal signing block is deliberately small. The output exists so the DS can be copied without reading the dashboard, and the lifecycle guard exists because destroying the resource is not a neutral act.

resource "cloudflare_zone_dnssec" "zone" {
  zone_id = var.zone_id
  status  = "active"

  lifecycle {
    prevent_destroy = true
  }
}

output "ds_record" {
  value = cloudflare_zone_dnssec.zone.ds
}

Enabling is a sequence with a wait in the middle. Activate the zone first, so Cloudflare is actually answering. Enable signing and wait for the status to settle. Read the DS and publish it at the registrar. Then validate from a resolver that checks signatures. Skipping the wait produces a window where the parent expects a key the zone has not finished publishing.

The DS is four values that must travel together. Key tag, algorithm, digest type and digest. Cloudflare's preferred algorithm is 13, which many registrar forms label "ECDSA Curve P-256 with SHA-256"; the digest type is commonly 2, or SHA-256. A registrar that accepts the fields but stores a different algorithm is not a registrar that supports your chain.

Algorithm support is a registry constraint, not a Cloudflare preference. If the registrar or the TLD cannot publish algorithm 13, the choices are to ask for support, move the registration, or run without DNSSEC. Quietly selecting a different algorithm to make a form accept the digest is not a workaround; the DS and the key it describes would no longer agree.

Cloudflare Registrar automates the parent half; most others do not. For domains registered there, Cloudflare submits DS records through CDS/CDNSKEY scanning, a process documented as taking one to two days with no manual timing control. Domains under .ch and .cz are also handled automatically. Everywhere else, a person or a registrar API copies the four values.

Terraform cannot publish the DS unless you also manage the registrar API. The signing resource ends at the zone boundary, and the DS output is data, not an action. A pipeline that applies the zone and stops there has signed the zone but not completed the chain; the missing step belongs in the runbook or in a second provider.

Copy the DS as one record, not four guesses. The computed output is already ordered as key tag, algorithm, digest type and digest, so paste the whole line into the change ticket and split it in that order. A registrar form that asks for the fields separately is not asking you to recompute anything; the values must match character for character. Note the zone and the date the copy came from, because re-enabling DNSSEC later can generate new key material with the same algorithm and a different digest.

Verification asks three different questions. Is the DS published at the parent? Does the authoritative server return DNSKEY and RRSIG records? Does a validating resolver mark the answer as authenticated? A single query cannot answer all three, which is why "DNSSEC is on" is not evidence.

Rollback runs parent-first, and the order is not negotiable. Remove the DS at the registrar, keep zone signing enabled until the parent's DS TTL has expired, and only then disable signing. Cloudflare's guidance suggests waiting at least 1.5 times the DS TTL before removing DNSKEY records, because a resolver still holding the old DS will keep checking against a key you deleted.

The dangerous move is destroying the signing resource while the DS is live. A terraform destroy that removes the DNSSEC resource stops signing immediately, while validators still hold a DS that points at the vanished key. The result is SERVFAIL for the whole zone, including mail and certificate issuance. prevent_destroy is not decoration here; it is the guard that turns a careless command into an error.

A stale DS is a migration failure, not a signing failure. If the domain was signed at the old provider, disable DNSSEC there and wait for the DS TTL to expire before changing nameservers. Cloudflare's migration guidance puts that wait at 24 to 48 hours for many TLDs. Moving first and cleaning up later is how a zone becomes unreachable while its authoritative server looks healthy.

Multi-signer is the zero-downtime exception. When the old provider can publish an external DNSKEY, dnssec_multi_signer lets both providers sign during the move, so the DS can change without an unsigned window. It is an Enterprise-shaped option, but it is the right answer when a 48-hour gap is not acceptable.

Figure 4 separates the two halves and puts the failure path beside the recovery path, because the order of operations is the whole lesson.

Zone signing and parent delegation are two halves of one chain Cloudflare signs the zone and produces a DS record. The registrar publishes that DS at the parent. Validators compare the two. Removing the DS first allows a safe rollback, while disabling signing before the DS expires produces SERVFAIL. One chain, two signers of the same decision Cloudflare zone: signing cloudflare_zone_dnssec publishes DNSKEY 257 and 256 signs each answer with RRSIG status active or disabled computed: ds, key_tag, digest, algorithm Terraform can read all four here Parent zone: delegation DS RRset at the registrar key tag, algorithm, digest type, digest cached for the parent's TTL Cloudflare Registrar: CDS scan, 1-2 days External registrar: manual or registrar API Terraform cannot write this row Validator: compares the DS it cached with the DNSKEY the zone serves A mismatch, a missing signature or a removed key becomes SERVFAIL, not an error page. Safe rollback, in order 1. Remove the DS at the registrar. 2. Keep signing until the DS TTL expires. 3. Set status disabled, then clean keys. Failure path, out of order 1. Disable or destroy signing first. 2. The DS still lives at the parent. 3. Every validating resolver returns SERVFAIL.

Diagnosis is a pair of queries, not a guess. If a validating resolver returns SERVFAIL and the same query succeeds with checking disabled, the records exist and the chain is what broke. Then compare the DS at the parent with the zone's DNSKEY; a key tag that matches nothing is a stale or wrong DS, not a bad record.

SymptomFirst checkLikely cause
SERVFAIL, works with +cdDS at parent versus DNSKEY in zoneStale DS or disabled signing
Zone pending after a provider moveOld DS still publishedDNSSEC not disabled before the NS change
DS correct, answers unsignedSigning status and RRSIG at the authoritative serverSigning never enabled, or disabled
Some resolvers fail, others workCache age and each resolver's validationThe DS TTL has not expired everywhere

The chain is only as good as its slowest cache. A correct apply does not clear a resolver that cached the old DS, and a correct rollback does not either. Plan the window around the TTL, not around the moment the dashboard turns green.

Import an Existing Record and Prove the Result

Adopting a record is a bind, not a create. The record already exists and already answers queries; import teaches Terraform its ID so future plans can manage it. Nothing about the record changes during the import itself, which is exactly why it is the safe way to bring an existing zone under control.

Find the record ID before writing any HCL. The ID is opaque, so guessing it is not an option. Ask the API for the record by name and type, and keep the response with the change record so the adoption can be audited later.

# Replace the zone ID and name with the values for your zone.
curl -s "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records?name=www.example.com&type=A" \
  -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  | jq '.result[] | {id, name, type, content, ttl, proxied}'

Write the block to match what exists, including the proxy flag. A proxied record needs automatic TTL and an explicit orange cloud; omitting the second one turns the adoption into a traffic change. Copy the value, the comment and any tags the API returned, because an unmanaged comment is still a diff waiting to happen.

The first plan after import is a diff, not a failure. Import fills state from the API; your configuration is a separate claim. A field that differs is either a mistake in the block or a value you do not actually want to manage. Resolve it before apply, and never import a record you have not decided to own.

An import block makes the adoption reviewable. Terraform 1.17 supports the declarative form, and the generated configuration can be written to a file for review instead of being typed from memory.

import {
  to = cloudflare_dns_record.www
  # Sample IDs. Use the zone and record IDs from your own API response.
  id = "023e105f4ecef8ad9ca31a8372d0c353/372d1f0a9c4b7e2f5a6d8c1b3e4f7a90"
}

resource "cloudflare_dns_record" "www" {
  zone_id = var.zone_id
  name    = "www.example.com"
  type    = "A"
  content = "192.0.2.10"
  ttl     = 1
  proxied = true
}

Then prove three separate things. An authoritative answer proves the zone is serving the record. A recursive answer proves the delegation and the cache path work. A no-change plan proves Terraform and Cloudflare agree about the record's desired state. Each one fails for a different reason, so a single successful query is not the finish line.

# Authoritative: ask one of the assigned nameservers directly.
dig @ns1.example.net www.example.com A +norecurse

# Recursive: ask a public resolver that validates and caches.
dig @1.1.1.1 www.example.com A

# Delegation: walk from the root to the parent's NS RRset.
dig NS example.com +trace

# Terraform: exit 0 means no changes, 2 means a diff, 1 means an error.
terraform plan -detailed-exitcode

The authoritative answer carries the aa flag. It comes from the server that owns the zone, and the TTL is the record's own value: 300 for a proxied record, the configured number for a grey one. If the answer is missing here, the record or the zone is wrong, and no amount of cache clearing will help.

The recursive answer carries ra and a counting-down TTL. The first query returns the remaining lifetime; a second query seconds later returns a smaller number. That is the cache doing its job. If the recursive answer differs from the authoritative one, you are looking at an old cache or a different delegation path, not a Terraform problem.

Use short output only for the value, never for the verdict. Short output strips the status line and the flags, so it can show an address while hiding a SERVFAIL on another type or the absence of the authoritative flag. Keep the full answer as evidence, and use the compact form for a quick glance.

No-change is an exit code, not a feeling. terraform plan -detailed-exitcode returns 0 when the plan is empty, 2 when there is a diff, and 1 when the plan failed. Wire the 0 into the adoption checklist, because a human reading "No changes" can be fooled by a plan that never refreshed.

Adopting one record must not disturb its neighbours. Count the zone's records before and after, and query a sibling that you did not import. A for_each that claims the whole zone will delete anything it does not list; an import of one record should leave every other record exactly where it was.

Capture evidence with the change, not after the incident. Save the API response for the record, the plan output and its exit code, and one authoritative and one recursive answer with the resolver address and a timestamp. A later argument about "what changed" is settled by four small files, while a dashboard screenshot shows only that a control panel rendered.

Lab

Adopt and verify DNS

Execution status: design-only. The commands below were not run against a live zone for this article. You perform the adoption and keep the output; the evidence is yours, not a transcript.

Prerequisites. A zone you can modify, an API token with DNS read and write on that zone, Terraform 1.17.1 with provider 5.28.1, and a resolver tool. Pick a record whose loss would be annoying but not fatal — a www address is a better first import than the apex.

  1. Capture the current state: query the record at the assigned nameserver and at a public resolver, and save both answers with timestamps.
  2. Find the record ID through the API and write it down next to the zone ID.
  3. Write the resource block to match the API response, including ttl = 1 and proxied = true for an orange-cloud record.
  4. Import with the declarative block, or run terraform import with the zone and record IDs.
  5. Plan. A field diff means the block is incomplete; fix it until the plan is empty. Do not apply a diff you cannot explain.
  6. Apply only when the plan is empty, then run the plan again with -detailed-exitcode and confirm exit code 0.
  7. Prove the answer at the authoritative server, at a recursive resolver, and at the parent for the NS RRset.
  8. Break it safely: change proxied to false, apply, and observe the answer shape change from edge addresses to the origin or target value. Then restore it and confirm the original answer returns. This is the rehearsal that makes the flag's meaning concrete.
CheckCommand shapePass looks like
Authoritativedig @assigned-ns name type +norecurseaa flag, answer from the zone
Recursivedig @1.1.1.1 name typera flag, TTL at or below the record's
Delegationdig NS zoneThe assigned nameservers, no extras
No-changeterraform plan -detailed-exitcodeExit code 0
NeighboursRecord count and a sibling queryUnchanged before and after

Expected observation. The imported record keeps its Cloudflare ID, the first plan either matches or explains itself, and the second plan is empty. The proxied answer returns edge addresses with TTL 300; the grey answer returns the origin value with the configured TTL. The authoritative and recursive answers agree once the cache has had time to expire.

Failure checks. A plan that wants to replace the record usually means the import bound the wrong ID or the block names a different zone. A plan that wants to flip proxied means the block omitted it. A recursive answer that disagrees with the authoritative one is a cache or delegation issue, not a state issue. A missing aa flag means you asked a recursive resolver, not the authoritative server.

Cost dimensions. DNS records and proxying are available on the Free plan for a normal zone; the exercise assumes no paid feature. A domain registration is typically USD 10–15 per year and registrar-dependent. DNSSEC signing is included, but the registrar must support the algorithm. No billable resource is created by the import itself.

Cleanup. Remove the imported resource from state if you want to stop managing it, or destroy it if you want the record gone; those are different actions and the plan will tell you which one you asked for. If the exercise enabled DNSSEC, remove the DS at the registrar and wait for its TTL before disabling signing. Do not delete the zone until the registrar points somewhere else.

References (checked 6 November 2026): DNS record resource, zone resource, DNSSEC resource, DNS setups, zone status, DNSSEC, DNSSEC troubleshooting, and import blocks.

Next in the Series

In TLS from Browser to Origin: Certificates, Modes and Origin Protection, we'll explore Treat edge TLS and origin TLS as separate connections and validate their certificate and trust requirements.