How to Automate DNS Records with Cloudflare API and Terraform
CloudflareTerraformDNSDevOpsInfrastructure as CodeAPI AutomationDeployment

How to Automate DNS Records with Cloudflare API and Terraform

PPlkdt Labs
2026-11-01
7 min read

A practical checklist for automating Cloudflare DNS records with Terraform, from API authentication and record types to validation and troubleshooting.

Managing DNS manually works until records become part of every deployment, environment, or verification workflow. This checklist shows how to automate Cloudflare DNS with its API and Terraform, including authentication, reusable record definitions, safe updates, validation, and troubleshooting for A, AAAA, CNAME, TXT, and MX records.

Overview

DNS automation means storing record definitions in a repeatable configuration and applying them through a controlled workflow instead of editing a dashboard for every change. Terraform is useful for this because the desired state is visible in code, reviewable before deployment, and reusable across environments. Cloudflare provides the DNS service and API, while the Terraform Cloudflare provider translates configuration into API operations.

Before changing anything, make three decisions:

  • Which zone is authoritative? Confirm that the domain uses Cloudflare nameservers. If another provider is authoritative, Cloudflare DNS configuration will not control public lookups for that zone.
  • Which records are managed by Terraform? Decide whether Terraform owns the entire zone or only selected records. Avoid having both Terraform and a dashboard, script, or hosting platform manage the same record.
  • Which values are environment-specific? Keep zone IDs, IP addresses, hostnames, verification tokens, and email destinations in variables or protected inputs rather than scattering them through configuration.

Use a narrowly scoped Cloudflare API token where possible, store it outside the repository, and provide it to Terraform through an environment variable or your CI/CD secret manager. Do not commit tokens, private keys, or production-only values to version control.

A minimal provider and record configuration can look like this:

terraform {
  required_providers {
    cloudflare = {
      source = "cloudflare/cloudflare"
    }
  }
}

provider "cloudflare" {
  api_token = var.cloudflare_api_token
}

variable "cloudflare_api_token" {
  type      = string
  sensitive = true
}

variable "zone_id" {
  type = string
}

resource "cloudflare_record" "app" {
  zone_id = var.zone_id
  name    = "app"
  type    = "A"
  content = var.app_ipv4
  ttl     = 300
  proxied = true
}

Provider arguments and resource attributes can change between provider releases, so pin and test the provider version used by your team rather than copying an example without checking its documentation. The important pattern is stable: authenticate securely, identify the zone, define the record, preview the change, and apply it deliberately.

Checklist by scenario

Website or API on an IPv4 address

  • Create an A record for the required hostname, such as app.example.com.
  • Use the server's public IPv4 address as content.
  • Choose Cloudflare proxying only when the service is compatible with it. For direct validation, unusual ports, or services that need the real client connection, DNS-only may be more appropriate.
  • Confirm that the web server, firewall, and TLS configuration also accept the hostname.

For a root domain, use the record name expected by the provider configuration, commonly @ or the zone's apex representation. Verify the syntax supported by the provider version you have pinned.

IPv6 support

  • Add an AAAA record only when the service is reachable and correctly configured over IPv6.
  • Confirm that the IPv6 address is stable and that firewall rules allow the intended traffic.
  • Test IPv4 and IPv6 separately. A working A record does not prove that the AAAA path works.

Connecting a service with a CNAME

Use a CNAME record when a hosting provider gives you a canonical hostname, such as project.hosting.example. This is the usual approach for many managed platforms and is the core pattern behind how to set a CNAME record through code.

resource "cloudflare_record" "www" {
  zone_id = var.zone_id
  name    = "www"
  type    = "CNAME"
  content = var.hosting_target
  ttl     = 300
  proxied = false
}

Check the hosting provider's instructions for whether proxying is supported. Keep the target hostname exactly as supplied, and avoid adding a protocol such as https:// to a DNS value.

Domain verification and other TXT records

TXT records are commonly used for service verification, SPF, and other published metadata. The value must be copied exactly, including punctuation and quotation-sensitive content. A Terraform example for adding a TXT record is:

resource "cloudflare_record" "verification" {
  zone_id = var.zone_id
  name    = "@"
  type    = "TXT"
  content = var.verification_value
  ttl     = 300
}

Do not casually replace an existing TXT record at the same name. A domain can have multiple TXT records, and verification, SPF, and other uses may coexist. Review the existing records before deciding whether to add, update, or remove one.

Email routing and MX records

MX records identify mail servers and use a priority value. Email providers often require more than one MX record, so model each destination separately and preserve the provider's priority order.

resource "cloudflare_record" "mail_primary" {
  zone_id  = var.zone_id
  name     = "@"
  type     = "MX"
  content  = var.primary_mail_host
  priority = 10
  ttl      = 300
}

Do not guess mail destinations, priorities, or related SPF, DKIM, and DMARC values. Use the instructions from the email provider, then validate the complete email authentication setup after applying it.

Separate staging and production

Use variables or separate Terraform workspaces and state arrangements to keep staging records distinct from production. A staging subdomain can be useful, but DNS isolation does not automatically prevent search indexing or public access. For a broader checklist, see how to create a staging subdomain and keep it out of search.

What to double-check

  1. Authentication: The API token should be available to Terraform, have the required zone permissions, and not be printed in logs.
  2. Zone identity: The zone ID must belong to the intended domain. A valid token paired with the wrong zone can still produce a successful but harmful change.
  3. Record ownership: Search the existing zone for duplicate A, CNAME, TXT, or MX records. A CNAME cannot generally coexist with other data at the same name.
  4. Proxy status: Proxying is not a universal setting. Review it independently for web traffic, verification records, mail, and non-HTTP services.
  5. TTL expectations: A short TTL can help during planned changes, but resolvers and local systems may continue using cached answers. TTL is not a guarantee of instant replacement.
  6. Terraform state: Protect the state file because it can contain sensitive values or infrastructure details. Use a controlled backend, access restrictions, and state locking where supported.
  7. Plan output: Run terraform fmt, terraform validate, and terraform plan before applying. Treat unexpected deletions or replacements as a stop signal.
  8. External resolution: Query authoritative nameservers and several public resolvers after the change. The DNS propagation checker guide explains how to verify records from more than one location.

For a deployment workflow, apply DNS changes separately from application changes when possible. This makes it easier to identify whether a failure comes from Terraform, DNS, the hosting platform, or the application itself. If an application is deployed with Docker, GitHub Actions, or Nginx, coordinate the hostname change with the corresponding deployment configuration; the Docker, GitHub Actions, and Nginx deployment guide covers related release concerns.

Common mistakes

  • Using a broad API key everywhere: Prefer a restricted token and keep separate credentials for local testing and automation.
  • Applying without importing existing records: If Terraform is taking ownership of records that already exist, determine whether they need to be imported or recreated. Otherwise, Terraform may propose unexpected changes.
  • Putting the full URL in a DNS record: A record value is usually an address or hostname, not a URL with a scheme and path.
  • Adding a second SPF record: Review existing TXT data and combine SPF mechanisms according to the email provider's instructions rather than publishing competing SPF records.
  • Assuming a successful API response means the service works: DNS can point correctly while the origin rejects the hostname, TLS certificate, port, or traffic path.
  • Changing nameservers while troubleshooting a record: First establish which nameservers are authoritative. Editing the wrong DNS provider creates confusion and delays.
  • Deleting records outside the codebase: If the configuration is authoritative, document ownership and review planned deletions before applying them.

If a record appears not to propagate, compare the authoritative answer with cached resolver answers before changing it again. Use this DNS not propagating diagnostic checklist and use dig, nslookup, or whois to identify delegation, caching, or record-value problems.

When to revisit

Revisit this DNS automation checklist before seasonal planning cycles, major launches, domain migrations, provider changes, and any workflow or tool update. It is especially useful when a team changes its hosting platform, introduces IPv6, adds a staging environment, changes email providers, or moves Terraform into CI/CD.

Before each planned change, use this short action list:

  1. Record the intended hostname, type, value, TTL, proxy setting, and owner.
  2. Check the current authoritative record and capture the expected before-and-after state.
  3. Update the Terraform configuration or variables, then run formatting, validation, and a plan.
  4. Review the plan with someone who understands the service being changed.
  5. Apply during a controlled window and retain the plan or deployment log.
  6. Verify authoritative DNS, public resolver responses, HTTPS or application behavior, and email delivery where relevant.
  7. Document the final record and remove temporary values when the change is complete.

Keep the configuration, provider version, token-handling process, and ownership notes current. That small maintenance habit turns Cloudflare DNS setup from a sequence of emergency dashboard edits into a repeatable, reviewable part of infrastructure as code.

Related Topics

#Cloudflare#Terraform#DNS#DevOps#Infrastructure as Code#API Automation#Deployment
P

Plkdt Labs

Editorial Team

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.