Last active
May 7, 2019 10:30
-
-
Save sbz/40383a56f815af2ae6cfb5bc5132b425 to your computer and use it in GitHub Desktop.
Detect useless ResourceRecord with type 'A' on AWS R53 pointing to private IP which doesn't exist in the region anymore
This file contains 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/env python3 | |
import ipaddress | |
import boto3 | |
from pprint import pprint as pp | |
# | |
# This script iterate over our regions in order to collect all the private IPs | |
# and check if the ResourceRecord created has still an existing IPs | |
# | |
regions = ['us-west-2', 'eu-central-1', 'us-east-2'] | |
zones = ['zoneIdUW2', 'zoneIdEC1', 'zoneIDUE2'] | |
def list_private_ip_instances(region): | |
private_ips = [] | |
client = boto3.client('ec2', region_name=region) | |
revs = client.describe_instances().get('Reservations') | |
for rev in revs: | |
if 'PrivateIpAddress' in rev['Instances'][0]: | |
private_ips.append(rev['Instances'][0]['PrivateIpAddress']) | |
return private_ips | |
def list_r53_records(zoneId, recordType='A'): | |
records = [] | |
client = boto3.client('route53') | |
response = client.list_resource_record_sets(HostedZoneId=zoneId) | |
for r in response['ResourceRecordSets']: | |
if 'ResourceRecords' in r: | |
if r['Type'] == recordType: | |
ip_value = r['ResourceRecords'][0]['Value'] | |
if not ipaddress.ip_address(ip_value).is_private: | |
continue | |
records.append({r['Name']: ip_value}) | |
return records | |
if __name__ == '__main__': | |
for region, zoneId in zip(regions, zones): | |
print(region, zoneId) | |
existing_private_ips = list_private_ip_instances(region) | |
for record in list_r53_records(zoneId): | |
if list(record.values())[0] not in existing_private_ips: | |
print("{} is useless".format(list(record.keys())[0])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example output with the zoneID and DNS entries redacted: