Skip to content

Instantly share code, notes, and snippets.

@epequeno
Created July 31, 2018 14:24
Show Gist options
  • Save epequeno/d2b1a9ce30b0114dbcd5b5ed8f66f4f5 to your computer and use it in GitHub Desktop.
Save epequeno/d2b1a9ce30b0114dbcd5b5ed8f66f4f5 to your computer and use it in GitHub Desktop.
audit how many IPs are in use by a list of subnets
"""subnet IP usage audit"""
# stdlib
from ipaddress import IPv4Network
# 3rd party
import boto3
# local
subnets = ['subnet-xxx']
def main():
ec2 = boto3.client('ec2', region_name='us-east-1')
for subnet in subnets:
result = ec2.describe_subnets(SubnetIds=[subnet])['Subnets'][0]
network = IPv4Network(result.get('CidrBlock'))
# aws reserves 3 addresses per subnet CIDR:
# https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Subnets.html#VPC_Sizing
max_possible_addresses = len(list(network.hosts())) - 3
available_ips = result.get('AvailableIpAddressCount')
percent_used = (available_ips / max_possible_addresses) * 100
fraction = f"{available_ips}/{max_possible_addresses}"
msg = f"{subnet} - {result.get('CidrBlock'):<18} {fraction:<7} {percent_used:.1f}%"
print(msg)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment