Purging Route53 Zones

The setup and tear-down of Route53 hosted zones doesn’t happen often. In order to delete a hosted zone all records except the NS and SOA records need to be deleted. This can be difficult if you have a zone with a few thousand records - common if you are seeding your reverse and forward lookups. When you are sure a zone needs to purged, you can lean on the below script to purge all records from a hosted zone while saving a backup locally.

#!/bin/bash
#
# purge-route53-zone.sh
# deletes all records in a Route53 hosted zone
# saving a backup to your home directory
#
# Usage:
# purge-route53-zone.sh HOSTED_ZONE_ID
#
# Requirements:
# aws-cli
# jq
#
HOSTED_ZONE=$1
# setup workspace
cd `mktemp -d`
aws route53 list-resource-record-sets --hosted-zone-id $HOSTED_ZONE \
| jq -c '.ResourceRecordSets[] | select((.Type != "NS") and (.Type != "SOA")) | {"Action":"DELETE","ResourceRecordSet":.}' > records
cp records ~/$HOSTED_ZONE.zone-backup
split -l 500 records
rm -rf records
ls | while read line; do
echo "purging $(wc -l $line | grep -o "[0-9]*") records"
record_sets=`mktemp --suffix="-$line"`
jq -s '{"Comment": "purging hosted zone","Changes":.}' $line > $record_sets
aws route53 change-resource-record-sets --hosted-zone-id $HOSTED_ZONE --change-batch=file://$record_sets
done
Share