Search code examples
amazon-web-servicesamazon-ec2aws-cliamazon-vpc

How do I find all the available private IP addresses within a subnet in AWS VPC


I want to find out all the available (unused) private IP addresses within a subnet in AWS VPC.

The below command would list out all the private IP addresses that have been used (unavailable) within a subnet in AWS VPC:

aws ec2 describe-network-interfaces --filters "Name=subnet-id,Values=<subnet-id>" | jq -r '.NetworkInterfaces[].PrivateIpAddresses[].PrivateIpAddress' --region <aws-region> | sort


Solution

  • I had a similar requirement and thought of creating a python code that may help. Please check how it goes.

    From: https://github.com/jagadishrajr/findfreeipinawssubnet

    import boto3
    import ipaddress, argparse
    
    ec2Client = boto3.client('ec2')
    parser=argparse.ArgumentParser()
    parser.add_argument("--subnetId", help="Provide subnetId", required=True)
    args=parser.parse_args()
    subnetId = args.subnetId
    
    descibeSubnets = ec2Client.describe_subnets(
        SubnetIds=[
            subnetId,
        ]
    )
    networkInterfaces = ec2Client.describe_network_interfaces(
        Filters=[
            {
                'Name': 'subnet-id',
                'Values': [
                    subnetId,
                ]
            }
        ]
    )
    for subnet in descibeSubnets['Subnets']:
        subnetCidrBlock = subnet['CidrBlock']
    usedIpList = []
    for interface in networkInterfaces['NetworkInterfaces']:
        usedIpList.append(interface['PrivateIpAddress'])
    
    allIpsInCidrBlock = [str(ip) for ip in ipaddress.IPv4Network(subnetCidrBlock)]
    
    # remove first four items from allIpsInCidrBlock as they are reserved for AWS
    allIpsInCidrBlock = allIpsInCidrBlock[4:]
    # remove last item from allIpsInCidrBlock as it is the broadcast address
    allIpsInCidrBlock.pop()
    # remove usedIpList items from allIpsInCidrBlock
    allIpsInCidrBlock = [ip for ip in allIpsInCidrBlock if ip not in usedIpList]
    for freeIp in allIpsInCidrBlock:
        print(freeIp)