Infrastructure as Code for DNS Record Management

Infrastructure as Code for DNS Record Management

Moving DNS records out of a web console and into version-controlled code is one of the most effective changes a team can make to DNS reliability and security. Infrastructure as code for DNS record management means every A, CNAME, MX and TXT record lives in a Git repository, gets reviewed like application code, and reaches the provider through an automated pipeline. This article covers the tooling, a practical migration path, the edge cases that break naive setups, and the mistakes that turn a clean idea into a new source of outages.

The immediate benefit is plain. When someone asks “who changed this record and why?”, the answer is a commit hash and a pull request rather than a shrug.

Why DNS Belongs in Version Control

Console-managed DNS has no memory. Cloudflare, Route 53 and Azure DNS all keep some form of audit log, but those logs show what changed. They rarely show why, and retention is often limited to 30-90 days depending on plan.

With records in code, the history is permanent and searchable. A reviewer sees the diff before it ships. A failed change can be reverted with git revert and a pipeline run, which makes the rollback procedures after a bad DNS change far less stressful than retyping values from memory at 2 a.m.

There is a security angle too. Dangling DNS records – CNAMEs that point at deprovisioned Heroku apps, Azure App Service instances or S3 buckets – are the raw material of subdomain takeover. Code makes those records visible and reviewable, which is the first step toward removing them.

Choosing a Tool for DNS Infrastructure as Code

Four tools cover most real-world setups. Terraform (or its open-source fork OpenTofu, created after HashiCorp’s license change in August 2023) uses providers such as hashicorp/aws for Route 53 and cloudflare/cloudflare. It fits teams already managing cloud resources in Terraform, because DNS records can reference the resources they point to.

OctoDNS, originally built at GitHub, is Python-based and defines zones in YAML. It runs in dry-run mode by default and only applies changes with the –doit flag. Its strength is syncing one zone definition to multiple providers at once, which matters for teams running dual-provider DNS for resilience.

DNSControl, created at Stack Exchange, uses a JavaScript-based configuration language with preview and push commands. It supports 50+ providers and handles registrar nameserver settings alongside zone records. Pulumi rounds out the list for teams that prefer TypeScript or Python over HCL.

An experienced platform engineer picks the tool that matches existing workflows rather than the one with the most GitHub stars. A team with 200 Terraform modules gains little from introducing a separate DNS tool.

A Migration Path That Avoids Surprises

Importing a live zone is where most problems start. Consider a common scenario: a team exports a zone of 340 records from Route 53, writes Terraform for the records they know about, and runs terraform plan. The plan looks clean. A month later they switch to OctoDNS for multi-provider sync, and the first dry run proposes deleting 41 records – Microsoft 365 verification TXT records, ACM validation CNAMEs, and a marketing landing page someone added through the console in 2022.

A disciplined migration usually follows this order:

  • Export the full zone from every provider and registrar, not just the primary one.
  • Generate code from the export (octodns-dump, DNSControl’s get-zones, or Terraform 1.5+ import blocks).
  • Run a plan or preview and confirm it shows zero changes before anyone edits anything.
  • Mark records owned by other systems as ignored, then lock console write access.
  • Make the first real change a small, low-risk one, such as a TTL adjustment.

The zero-diff check is the step people skip. If the first plan shows changes, the code does not yet describe reality, and applying it will alter production DNS. If the migration also involves a provider switch, the guidance on migrating DNS providers without downtime or data loss applies – lower TTLs to 300 seconds 24-48 hours before cutover.

Edge Cases Where Full Code Ownership Does Not Fit

Not every record should be in your repository. Kubernetes clusters running ExternalDNS create and delete records automatically as Ingress objects change. Managing those same records in Terraform creates a tug-of-war where each system overwrites the other. Scope ExternalDNS to a dedicated subdomain like k8s.example.com, or use its TXT ownership registry and exclude those names from your IaC tool.

The same applies to records created by automation you do not control: ACM and Let’s Encrypt DNS-01 challenge records, SaaS verification tokens, and subdomains delegated to another team’s zone. DNSControl offers IGNORE() and NO_PURGE, OctoDNS supports ignored records per provider, and Terraform only manages what is in its state.

Very small teams are another exception. A five-person company with one domain and 15 records that change twice a year may find a pipeline adds more overhead than value. A documented export stored in Git can be enough. Regulated environments sit at the other extreme – under SOC 2, ISO 27001 or NIS2, pull request approvals double as change-management evidence, which alone often justifies the effort.

Common Mistakes Practitioners Make

The first mistake is partial ownership with a tool that assumes full ownership. OctoDNS and DNSControl treat the configuration as authoritative for the whole zone by default. Anything not in code is a deletion candidate. Teams that manage “just the important records” in code and leave the rest in the console are one careless apply away from deleting their SPF record.

The second is hardcoding targets as strings. A CNAME written as “myapp.azurewebsites.net” survives after the App Service is destroyed – a textbook dangling record. Referencing the resource attribute directly (for example, aws_cloudfront_distribution.site.domain_name) ties the record’s lifecycle to the resource, so destroying one removes or breaks the other visibly in the plan.

The third is over-privileged pipeline credentials. A Cloudflare global API key in a CI variable gives anyone who can modify a workflow file control over every zone in the account. Use scoped API tokens limited to DNS edit on specific zones, and an IAM role restricted to route53:ChangeResourceRecordSets on named hosted zones.

The Myth That Code Eliminates Drift

A widespread belief holds that once DNS is in code, the live zone always matches the repository. It does not. Console access gets restored during an incident. A registrar support agent changes nameservers. An attacker with stolen credentials adds a TXT record for domain verification on a service they control.

IaC only detects drift when someone runs a plan. Scheduling a read-only plan every few hours in CI and alerting on any non-empty diff closes part of the gap. Comparing the live zone against baseline snapshots for detecting unauthorized changes closes more, because external monitoring also catches subdomains that never made it into code at all.

Code also does not verify that targets still exist. A perfectly reviewed CNAME to a deleted Fastly service is still a takeover risk. Continuous DNS monitoring and subdomain discovery complement IaC rather than replace it.

FAQ

Can Terraform and OctoDNS manage the same zone?
Technically yes, but only with strict separation. Assign each tool non-overlapping record names and configure each to ignore the other’s records. In practice, one tool per zone is far easier to operate.

How should DNSSEC be handled with infrastructure as code?
Most managed providers, including Cloudflare and Route 53, sign zones automatically once DNSSEC is enabled. Manage the enablement flag and the DS record at the registrar in code, but let the provider handle key rotation.

What TTL should code-managed records use?
3600 seconds suits most stable records. Drop to 300 seconds ahead of planned changes, and keep failover or load-balanced records at 60-300 seconds.

Summary

Infrastructure as code turns DNS from an undocumented console state into a reviewed, reversible, auditable system. Start with a zero-diff import, define clearly which records your tool owns, reference resources instead of hardcoding hostnames, and scope pipeline credentials tightly. Then treat code as one layer of defense: schedule drift detection and keep external monitoring running, because the riskiest records are often the ones nobody ever wrote down.