Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Want to delete a lot of old hosted zones on Route53? This should take the pain away.

AWS Route53 Hosted Zone Cleaner

Why?

My org buys lots of domains and configure lots of records on AWS. Removing them is a pain though; you have to remove each record set before you can remove the hosted zone. This makes it much more straightforward.

Feel free to use this; but you're on your own. I am not responsible if you break something.

Setup

You'll need ruby/ruby-gems and your AWS API credentials.

From your terminal:

$ gem install aws-sdk # these instructions are based on v2.1.13

$ export AWS_ACCESS_KEY_ID="your key id here"

$ export AWS_SECRET_ACCESS_KEY="secret here"

$ aws.rb # should load an AWS REPL

Nuke it from Orbit

The rest of these commands are run inside the AWS REPL.

Grab the Hosted Zones

zones = route53.list_hosted_zones.hosted_zones.select{|z| z.name =~ /PATTERN/}

e.g. PATTERN might be: socialjustice(|map)\.com\.$ (matches socialjustice.com., socialjusticemap.com., but not the .au variants)

CONFIRM which Hosted Zones you're about to delete:

zones.map(&:name)

NB: be SUPER SURE it shows what you want to nuke. 😱 There's no going back from the next step.

Delete Resource Record Sets inside each Hosted Zone

Seriously, you confirmed your regex pattern, right? All of the domains listed in your terminal are about to be deleted with no back up.

This deletes all of the A, CNAME, etc. record sets, but leaves the undeletable NS & SOA records.

zones.map(&:id).each{|id| route53.list_resource_record_sets({hosted_zone_id: id}).resource_record_sets.reject{|rs| rs[:type] == "NS" || rs[:type] == "SOA"}.each{|record_set| route53.change_resource_record_sets({hosted_zone_id: id, change_batch: {changes:[{action: "DELETE", resource_record_set: record_set}]}})}}

OMG, so many brackets... :shipit:

Delete the Hosted Zones

zones.map(&:id).each{|id| route53.delete_hosted_zone({id: id}) }

And you're done. 💃

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment