Sub topic 10
Automating record changes with the AWS CLI
This chapter assumes you have a public hosted zone, you know the record types from earlier chapters, and the AWS CLI (version 2) is installed with credentials that allow route53:ChangeResourceRecordSets, route53:ListResourceRecordSets, route53:ListHostedZonesByName and route53:GetChange. You should be comfortable with JSON and basic shell scripting.
Why use change batches
The console works well for one-off edits. It does not give you a reviewable, repeatable record of what you changed. The Route 53 API accepts every record change as a change batch: a JSON document that lists the changes to make. You can keep a change batch in version control, review it in a pull request, and apply the same file to a staging zone and a production zone.
Three properties of change batches shape how you write automation:
- A batch is atomic. Route 53 applies every change in the batch or none of them. If the fifth change is invalid, the first four are not applied.
- A batch is not instant. The API call returns quickly with a status of
PENDING. The status becomesINSYNConce the change has reached all of the zone's authoritative name servers, which usually takes under a minute. - A batch has limits. One request can contain at most 1,000 record elements, and the API allows about five requests per second per AWS account. Group related changes into one batch instead of sending many small calls.
The three actions
Each entry in Changes has an Action and a ResourceRecordSet.
| Action | What it does | Fails when |
|---|---|---|
| `CREATE` | Adds a record set | A record set with the same name, type and set identifier already exists |
| `UPSERT` | Creates the record set, or replaces it if it exists | The batch is malformed (it does not fail on existence) |
| `DELETE` | Removes a record set | The record set is missing, or any value you send differs from what is stored |
UPSERT is the right default for automation because running the same script twice gives the same result. Use CREATE when you want a hard failure if something already exists, for example to avoid overwriting a record that another team owns.
Find the hosted zone ID
Every record command needs the hosted zone ID. Look it up by name instead of copying it by hand:
aws route53 list-hosted-zones-by-name \
--dns-name example.com \
--query "HostedZones[?Name=='example.com.'].Id | [0]" \
--output textTwo details matter here. Route 53 stores and returns names with a trailing dot, so the filter compares against example.com.. The list-hosted-zones-by-name call also returns zones that sort after the name you give, even if no zone matches, which is why the query filters on the exact name. The ID comes back as /hostedzone/Z0123456789ABC. The CLI accepts that form, and you can strip the prefix with ${ZONE_ID##*/} if you prefer.
If you have both a public and a private zone with the same name, this query returns the first match only. Add Config.PrivateZone==\false\`` to the filter, or look up the zone by ID, to avoid editing the wrong one.
Create or update a record
Save this change batch as www-a-record.json:
{
"Comment": "Create or update the www A record",
"Changes": [
{
"Action": "UPSERT",
"ResourceRecordSet": {
"Name": "www.example.com",
"Type": "A",
"TTL": 300,
"ResourceRecords": [{ "Value": "192.0.2.10" }]
}
}
]
}Then submit it:
aws route53 change-resource-record-sets \
--hosted-zone-id ZONE_ID \
--change-batch file://www-a-record.jsonThe response contains a ChangeInfo object with an Id such as /change/C0123456789ABC and a Status of PENDING. Check the status later with aws route53 get-change --id C0123456789ABC, or block until it finishes:
aws route53 wait resource-record-sets-changed --id C0123456789ABCThe waiter polls every 30 seconds and gives up after 60 attempts, so it works as a gate between "submitted" and "safe to continue" in a deployment script.
INSYNC only tells you the Route 53 name servers have the new data. Resolvers that cached the old answer keep serving it until the old TTL expires, so a 300-second TTL means up to five more minutes before every client sees the change.
Aliases and multi-record batches
An alias record uses AliasTarget in place of TTL and ResourceRecords. This batch points the zone apex at a CloudFront distribution, where a CNAME is not allowed:
{
"Changes": [
{
"Action": "UPSERT",
"ResourceRecordSet": {
"Name": "example.com",
"Type": "A",
"AliasTarget": {
"HostedZoneId": "Z2FDTNDATAQYW2",
"DNSName": "d111111abcdef8.cloudfront.net",
"EvaluateTargetHealth": false
}
}
}
]
}Z2FDTNDATAQYW2 is the fixed zone ID for every CloudFront alias target. For other targets, such as load balancers, the zone ID is specific to the service and Region, so read it from the resource's own description instead of reusing this value.
Atomicity is most useful when records must change together. A weighted rollout needs two records for the same name, each with a unique SetIdentifier:
{
"Changes": [
{
"Action": "UPSERT",
"ResourceRecordSet": {
"Name": "app.example.com",
"Type": "A",
"SetIdentifier": "blue",
"Weight": 90,
"TTL": 60,
"ResourceRecords": [{ "Value": "192.0.2.20" }]
}
},
{
"Action": "UPSERT",
"ResourceRecordSet": {
"Name": "app.example.com",
"Type": "A",
"SetIdentifier": "green",
"Weight": 10,
"TTL": 60,
"ResourceRecords": [{ "Value": "192.0.2.30" }]
}
}
]
}Because both entries share one batch, no resolver ever sees one record updated and the other stale. To shift traffic later, edit the two weights and apply the file again.
Inspect before you change
Read the current state first. The --query option uses JMESPath, so you can filter without extra tools:
aws route53 list-resource-record-sets \
--hosted-zone-id ZONE_ID \
--query "ResourceRecordSets[?Name=='www.example.com.' && Type=='A']"Saving this output before a change gives you a rollback source. Record names in the output end with a dot, and a wildcard record appears with the asterisk escaped as \052, so *.example.com is returned as \052.example.com.. Use the escaped form in --query filters.
For long zones, list-resource-record-sets returns pages. The CLI follows the pages for you unless you pass --max-items.
A complete update script
This script ties the pieces together. It finds the zone, builds a batch, submits it, and waits for INSYNC. It stops on any error.
#!/usr/bin/env bash
set -euo pipefail
ZONE_NAME="example.com."
RECORD_NAME="www.example.com"
NEW_IP="${1:?usage: $0 IPV4_ADDRESS}"
TTL=300
ZONE_ID=$(aws route53 list-hosted-zones-by-name \
--dns-name "$ZONE_NAME" \
--query "HostedZones[?Name=='${ZONE_NAME}'].Id | [0]" \
--output text)
if [[ -z "$ZONE_ID" || "$ZONE_ID" == "None" ]]; then
echo "No hosted zone named $ZONE_NAME" >&2
exit 1
fi
ZONE_ID="${ZONE_ID##*/}"
BATCH=$(cat <<EOF
{
"Comment": "Set ${RECORD_NAME} to ${NEW_IP}",
"Changes": [
{
"Action": "UPSERT",
"ResourceRecordSet": {
"Name": "${RECORD_NAME}",
"Type": "A",
"TTL": ${TTL},
"ResourceRecords": [{ "Value": "${NEW_IP}" }]
}
}
]
}
EOF
)
CHANGE_ID=$(aws route53 change-resource-record-sets \
--hosted-zone-id "$ZONE_ID" \
--change-batch "$BATCH" \
--query "ChangeInfo.Id" \
--output text)
CHANGE_ID="${CHANGE_ID##*/}"
echo "Submitted change $CHANGE_ID, waiting for INSYNC..."
aws route53 wait resource-record-sets-changed --id "$CHANGE_ID"
echo "Done: ${RECORD_NAME} -> ${NEW_IP}"Run it as ./update-www.sh 192.0.2.10. The ${1:?...} expansion makes the script exit with a usage message when the argument is missing. Interpolating a value into JSON this way is safe only for input you control. If the value comes from outside your team, validate it first, because a quote character in it would break the JSON or change the batch.
Deleting records
DELETE must repeat the record exactly as stored: same name, type, TTL, set identifier, and every value. A mismatch returns an InvalidChangeBatch error saying the record was not found. The reliable approach is to copy the record from list-resource-record-sets output into the batch, then change only Action to DELETE.
Common errors
| Error message (summary) | Cause | Fix |
|---|---|---|
| `InvalidChangeBatch`: record already exists | `CREATE` for an existing name and type | Use `UPSERT`, or check the current records |
| `InvalidChangeBatch`: record not found | `DELETE` with a value, TTL or set identifier that differs from the stored record | Copy the record exactly from `list-resource-record-sets` |
| `InvalidChangeBatch`: CNAME conflicts with other records | A CNAME shares a name with another record type | Use an alias record, or remove the other record |
| `InvalidInput`: invalid value | TXT value not wrapped in double quotes, or a bad IP address | Quote TXT data as `"\"v=spf1 -all\""` inside JSON |
| `Throttling`: Rate exceeded | More than about five API requests per second | Combine changes into fewer batches, and retry with a delay |
| `NoSuchHostedZone` | Wrong zone ID, or wrong AWS account or profile | Check the ID and run `aws sts get-caller-identity` |
A failed batch changes nothing, so it is safe to correct the file and submit it again.
Verifying the result
After the waiter reports INSYNC, ask a Route 53 name server directly, which bypasses resolver caches. Use one of your zone's own name servers:
dig @ns-123.awsdns-45.com www.example.com A +norecurseThen run dig www.example.com A against your normal resolver. If the two answers differ, the resolver is serving a cached record and will update when the old TTL expires. The next chapter covers this in more detail.
Exercise
A change batch contains an UPSERT for www.example.com and a CREATE for mail.example.com, but mail.example.com already exists. What happens to the www record, and how would you change the batch so that it succeeds when you re-run it?
Show answer
Nothing is applied, including the www record, because a change batch is atomic and the failing CREATE makes the whole batch return InvalidChangeBatch. Change the CREATE to an UPSERT so the batch no longer fails when the record exists, and re-run it. This also makes the file safe to apply repeatedly.
Exercise
You submit a batch that lowers the TTL on www.example.com from 3600 to 60 seconds, and get-change reports INSYNC. A colleague says some users may still see the old address for up to an hour. Is the colleague right, and why?
Show answer
Yes. INSYNC means only that the Route 53 name servers have the new record. Resolvers that cached the old answer under the 3600-second TTL keep it until that TTL expires, so some clients can see the old address for up to an hour. The new 60-second TTL applies to answers fetched after the change. To avoid this, lower the TTL well ahead of a planned change.