Skip to content

Instantly share code, notes, and snippets.

@akinnard
Last active February 22, 2019 04:14
Show Gist options
  • Save akinnard/de56e3338bfdedb284767298681320d1 to your computer and use it in GitHub Desktop.
Save akinnard/de56e3338bfdedb284767298681320d1 to your computer and use it in GitHub Desktop.
Clean up a private hosted zone in route53
#!/usr/local/bin/python3
import sys
import boto3
import argparse
import requests
import json
from datetime import datetime
from colorama import Fore, Back, Style
MYDATE = '{0:%Y%m%d}'.format(datetime.now())
curVersion = "0.0.1"
startDateTime = datetime.now()
parser = argparse.ArgumentParser()
parser.add_argument('-v', "--version", dest = "showVersion", action='store_true')
parser.add_argument("-p", "--profile",dest = "awsProfile", default = "ahalogy-prod", help="AWS Profile to use")
parser.add_argument("-z", "--hosted-zone",dest = "hostedZone", help="AWS Hosted Zone to cleanup")
args = parser.parse_args()
def diff_dates(date1, date2):
return abs(date2-date1)
def halt_run():
endDateTime = datetime.now()
elapsedTime = diff_dates(endDateTime,startDateTime)
print("Elapsed Time: {}".format(elapsedTime))
print("Run ended on {}".format(endDateTime))
# TODO: Add elapsed time to output
print(Fore.BLUE + "********************************************************************************"+ Style.RESET_ALL)
def hr_line():
print(Fore.BLUE + "--------------------------------------------------------------------------------"+ Style.RESET_ALL)
def header():
print(Fore.BLUE + "********************************************************************************"+ Style.RESET_ALL)
print("Route53 Cleanup Utility, script version {}".format(curVersion))
print("Run started on {}".format(startDateTime))
hr_line()
def alert_message(message):
print(Fore.CYAN +"{}".format(message)+ Style.RESET_ALL)
print(Fore.RED + "{}".format(e) + Style.RESET_ALL)
hr_line()
halt_run()
sys.exit()
# --------------------------------------------------------------------------------
# Begin Body
# --------------------------------------------------------------------------------
# Print header
header()
if args.showVersion == True:
halt_run()
sys.exit()
# Connect to AWS using a local profile
try:
awsSession = boto3.Session(profile_name=args.awsProfile)
except Exception as e:
alert_message("Error connecting awsProfile to AWS:")
# Get session information from STS
try:
sts = awsSession.client('sts').get_caller_identity()
awsArn = sts["Arn"]
awsAccount = sts["Account"]
awsUser = awsArn.split('/')[-1]
except Exception as e:
alert_message("Error getting awsProfile name from AWS: ")
print("AWS profile user: {}".format(awsUser))
print("Hosted Zone: {}".format(args.hostedZone))
# Get Zone information from AWS
try:
hostedZoneInfo = awsSession.client('route53').get_hosted_zone( Id=args.hostedZone )
except Exception as e:
alert_message("Error getting Hosted Zone name from AWS: ")
hzName = hostedZoneInfo["HostedZone"]["Name"].strip()
hzResourceCount = hostedZoneInfo["HostedZone"]["ResourceRecordSetCount"]
hzComment = hostedZoneInfo["HostedZone"]["Config"]["Comment"].strip()
print("Hosted Zone Name: {}".format(hzName))
print("Hosted Zone Comment: {}".format(hzComment))
print("Resource Record Count: {}".format(hzResourceCount))
hr_line()
# Get all the records for the hosted zone to loop over
try:
recordSets = awsSession.client('route53').list_resource_record_sets(
HostedZoneId=args.hostedZone
)
except Exception as e:
alert_message("Error getting HostedZone Record Set from AWS: ")
# Loop over all the records
for x in recordSets["ResourceRecordSets"]:
dnsType = x["Type"]
dnsName = x["Name"]
dnsTTL = x["TTL"]
dnsRRValue = x["ResourceRecords"][0]["Value"]
# We only want the cname recordds
if dnsType == "CNAME" :
print("Type: {} - Name {} - Value {}".format(dnsType,dnsName,dnsRRValue))
# Search ec2 for the private dns record
try:
ec2Instance = awsSession.client('ec2').describe_instances ( Filters=[{'Name':'private-dns-name', 'Values':[dnsRRValue]}])
except Exception as e:
alert_message("Error getting ec2 Record from AWS: ")
reservationRecords = ec2Instance["Reservations"]
resorvationCount = len(reservationRecords)
print("Instances Found: {}".format(resorvationCount))
# If no record sets where found for that private dns record
if resorvationCount == 0:
# ask user if they want to delete the record
toDelete = input("Should we delete this record (y/n)")
# issue a change batch request
if toDelete == "y":
changeRecord = awsSession.client('route53').change_resource_record_sets(
HostedZoneId=args.hostedZone,
ChangeBatch={
'Comment': 'R53 Cleapup script',
'Changes': [
{
'Action': 'DELETE',
'ResourceRecordSet': {
'Name': dnsName,
'Type': dnsType,
'TTL': dnsTTL,
"ResourceRecords": [
{
"Value": "{}".format(dnsRRValue)
},
]
}
},
]
}
)
print("DELETED {}".format(dnsName))
hr_line()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment