Created
February 15, 2021 07:52
-
-
Save blofeldthefish/0bab3da05da48a7052beb7c594570888 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/bash | |
# | |
# If an EC2 Instance tag Name matches a record in DNS (Route53) and the EC2 Instance is removed without Tidying Route53 Zone, | |
# This script will find the "orphaned" Zone records, and remove them. | |
# | |
rm -f /tmp/delete-r53.json | |
ZONEID=$(aws route53 list-hosted-zones-by-name |jq -r '.HostedZones[]|select (.Config.PrivateZone)|select (.Name|contains("example.com"))|.Id') | |
# | |
# Get a list of all DNS Records which don't have a running instance | |
# | |
RECORDSTOREMOVE=$(comm -23 <(aws route53 list-resource-record-sets --hosted-zone-id $ZONEID|jq -r '.ResourceRecordSets[]|select (.Name|startswith("my-app"))|(.Name| split("."))[0]'|sort) <(aws ec2 describe-instances --filters "Name=tag:Name,Values=my-app*"|jq -r '.Reservations[].Instances[].Tags[]|select (.Key=="Name")|(.Value|split(" "))[0]'|sort)|jq --slurp --raw-input 'split("\n")[:-1]') | |
# | |
# Generate JSON String of changes to delete discovered Records | |
# | |
aws route53 list-resource-record-sets --hosted-zone-id $ZONEID|jq --argjson toremove "$RECORDSTOREMOVE" '[.ResourceRecordSets[] |select ([.Name|split(".")[0]]|inside($toremove))|{Action: "DELETE", ResourceRecordSet: {Name: .Name, ResourceRecords: .ResourceRecords,Type: .Type, TTL: .TTL }}]|{Comment: "Bye Bye Superfluous Records",Changes: .}' > /tmp/delete-r53.json | |
# | |
# Provide basic feedback | |
# | |
[ $(grep Name /tmp/delete-r53.json|wc -l) -eq 0 ] && echo "No superfluous records" && exit | |
grep Name /tmp/delete-r53.json | |
grep Name /tmp/delete-r53.json|wc -l | |
read -n 1 -s -r -p "Looking good ? - press ctrl C if not!!" | |
# | |
# Make it happen! | |
# | |
aws route53 change-resource-record-sets --hosted-zone-id $ZONEID --change-batch file:///tmp/delete-r53.json |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment