Manage internal DNS hostnames with infrastructure code that gives each logistics tenant an explicit entry in deployment intent, then compares that intent with published records. A small, deterministic reconciler is the least complex starting point when the deployment already knows which tenants should exist.
TL;DR: Manage internal DNS hostnames from infrastructure code by reading current records, computing a diff, applying approved changes, and reading back the result. Treat an absent tenant as an unresolved lifecycle decision until an explicit retirement authorizes deletion. The useful deployment artifact is the difference between intended and published records.
For a logistics application, a hostname might identify the tenant endpoint used by a shipment assistant or retrieval service. The interesting boundary is between tenant onboarding and tenant retirement: creation should be automatic, but a shortened tenant inventory should not silently become permission to remove names. Keep that distinction in code. It gives a notebook-to-prod workflow a concrete invariant to evaluate before connecting a DNS adapter.
How should infrastructure code manage internal DNS hostnames when tenants retire?
Use three inputs: desired tenant records, observed published records, and explicit retirement intent. The planner produces changes; the deployment applies them through a DNS adapter; a fresh observation checks whether publication matches intent. Keep the observation timestamp and deployment revision with that result so the next operator can tell which intent was checked.
An empty diff only describes its input snapshot. Check its age.
The reader searching for a Node.js deploy-and-diff example needs the same data flow, but the implementation below uses Python. It is deliberately small enough to run as a script or notebook cell. The published-record mapping is an in-memory stand-in for a DNS adapter, so this example demonstrates reconciliation without making network calls or claiming to configure a real zone. Names and addresses are illustrative.
Start with a runnable lifecycle example
The desired state contains two tenants: harbor and depot. The observed state has an old address for harbor, a retired tenant called quay, and a shared metrics name. Only tenant names in the declared ownership scope can change. A missing desired entry alone cannot authorize a deletion.
from ipaddress import IPv4Address
SUFFIX = ".tenants.example.com"
def validate(records):
for name, address in records.items():
if not name.endswith(SUFFIX):
raise ValueError(f"Outside tenant scope: {name}")
tenant = name[:-len(SUFFIX)]
if not tenant or "." in tenant:
raise ValueError(f"Expected one tenant label: {name}")
if len(tenant) > 63 or not tenant.isascii():
raise ValueError(f"Invalid tenant label: {name}")
if tenant[0] == "-" or tenant[-1] == "-":
raise ValueError(f"Invalid tenant label: {name}")
if not all(c in "abcdefghijklmnopqrstuvwxyz0123456789-"
for c in tenant):
raise ValueError(f"Invalid tenant label: {name}")
IPv4Address(address)
def plan(desired, observed, owned, retired):
validate(desired)
if not set(desired) <= owned or not retired <= owned:
raise ValueError("Intent exceeds declared ownership")
if set(desired) & retired:
raise ValueError("A tenant cannot be active and retired")
changes = []
for name in sorted(desired):
if observed.get(name) != desired[name]:
changes.append(("set", name, desired[name]))
for name in sorted(retired):
if name in observed:
changes.append(("delete", name, None))
return changes
def apply_in_memory(snapshot, changes):
result = dict(snapshot)
for action, name, address in changes:
if action == "set":
result[name] = address
elif action == "delete":
result.pop(name, None)
else:
raise ValueError(f"Unknown action: {action}")
return result
desired = {
"harbor.tenants.example.com": "192.0.2.10",
"depot.tenants.example.com": "192.0.2.20",
}
observed = {
"harbor.tenants.example.com": "192.0.2.9",
"quay.tenants.example.com": "192.0.2.30",
"metrics.example.com": "192.0.2.40",
}
retired = {"quay.tenants.example.com"}
owned = set(desired) | retired
changes = plan(desired, observed, owned, retired)
for change in changes:
print(change)
published = apply_in_memory(observed, changes)
assert plan(desired, published, owned, retired) == []
assert published["metrics.example.com"] == observed["metrics.example.com"]
This produces 3 changes: set depot, replace harbor's address, and delete quay. The second plan is empty. The shared metrics record survives. These are properties of the sample data and assertions, not a claim about an external service. The validator caps the tenant label at 63 characters and accepts only lowercase ASCII letters, digits, and interior hyphens; this is an intentionally restricted input policy.
The code models one IPv4 address per tenant hostname. That narrow representation keeps the lifecycle decision visible, but it cannot represent arbitrary DNS record sets. A production adapter needs an explicit record model covering owner name, type, values, and TTL. Reject unsupported input rather than squeezing multiple addresses or unrelated record types into this mapping. DNS resource records and caching behavior are described in RFC 1034 and RFC 1035; dynamic update semantics are specified separately in RFC 2136.
Carry the plan across the deployment boundary
The important trade-off is explicit retirement versus automatic cleanup. Automatic cleanup removes inventory maintenance work, but it also turns an incomplete inventory into deletion intent. Don't infer retirement. For tenant onboarding, keep retirement explicit and persist ownership independently of the latest desired-state file. The sample constructs ownership locally for readability; deployment code should load an authoritative ownership inventory and reject unexpected scope expansion.
Now consider a deployment that plans against snapshot A while another deployment changes a tenant record. Applying the earlier plan without checking its assumptions can overwrite the newer intent. Serialize mutations for the same naming scope, or use an adapter that can enforce suitable update prerequisites. RFC 2136 defines prerequisites for DNS UPDATE; support in a particular management interface needs separate verification. Do not assume a generic record API exposes them.
A preview should therefore carry the intent revision, the observed snapshot, and the proposed changes together. Recheck the relevant state immediately before mutation. If it differs, produce a fresh diff and review that result under the same deployment policy. After applying, read published records again and compare their normalized representation with the desired records and retirement conditions. A successful write response alone is an insufficient completion rule for this design.
Read back deliberately.
For internal naming, choose an observation point that matches the question being asked. Checking the publishing authority establishes one kind of evidence; checking the resolver used by the shipment assistant establishes another. DNS caching means those observations can differ during a transition. Record both when diagnosing a cutover, and avoid claiming that every client has converged just because one read matches. Keep endpoint readiness and application routing as separate checks: an address match does not prove the tenant request reaches a healthy application.
Make the notebook earn its production boundary
Start the eval harness with lifecycle cases, not a live mutation. The example already checks convergence and preservation of a shared name. Add cases for a tenant omitted without retirement, conflicting active and retired intent, an address change, an invalid label, and a stale observation. The omitted tenant should remain untouched while the deployment reports unresolved inventory. A planner returning no mutations must not hide that discrepancy from the operator.
Deterministic planning makes this pleasantly testable. No model needed.
For a RAG or agent application, tenant identity should come from an authoritative application record. Keep a model-generated suggestion outside the mutation boundary until ordinary validation and authorization accept it. The planner has no reason to spend prompt tokens deciding whether two address strings match. Reserve model calls for work that needs language understanding, and give operational summaries a bounded diff instead of repeatedly attaching a full zone snapshot. That is a prompt-cost-aware design choice, without making pricing the argument.
The production adapter is where errors become concrete. On a timeout, observe state before retrying; on partial completion, recompute the remaining changes from fresh state. Avoid blindly replaying the old batch. Treat rollback as another plan against current publication, because the old snapshot may no longer describe changes made by other deployments. Keep the intended revision, mutation results, and read-back discrepancy available together for diagnosis.
Close the deployment with evidence
Before enabling automatic tenant creation, check that the tenant inventory, ownership boundary, and retirement source are explicit. Validate the preview against lifecycle fixtures, then require a fresh observation before mutation. Finish each deployment with a recorded comparison between intent and publication, plus a separate application readiness result.
For the logistics workflow, declare success when each active tenant has its intended record, each authorized retirement has completed, and unrelated records remain untouched. Report unresolved inventory and stale observations as distinct states. That gives the team a useful operational contract: automatic subdomains with a visible explanation for every change.
References
The DNS specifications support the record, caching, and update distinctions above. The lifecycle policy and reconciliation example are an implementation design, rather than requirements imposed by those specifications. RFC 7489 addresses domain email authentication; it does not specify deployment reconciliation for tenant hostnames.
Further reading
- RFC 1034, Domain Names — Concepts and Facilities: https://datatracker.ietf.org/doc/html/rfc1034
- RFC 1035, Domain Names — Implementation and Specification: https://datatracker.ietf.org/doc/html/rfc1035
- RFC 2136, Dynamic Updates in the Domain Name System: https://datatracker.ietf.org/doc/html/rfc2136
- RFC 5737, IPv4 Address Blocks Reserved for Documentation: https://datatracker.ietf.org/doc/html/rfc5737
- RFC 7489, Domain-based Message Authentication, Reporting, and Conformance: https://datatracker.ietf.org/doc/html/rfc7489
Top comments (0)