Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

amazon web services - How to calculate total ip's of a subnet in AWS

Recently we got an issue of IP running out in VPC due to huge IP's consumed by ENI. I need to write a script in boto3, to trigger an alert if total ip usage increases around 80% or something.

Hence I need to know the Total ip's allocated in a subnet in VPC. I need the total count of used IP's and free IP's.

Please share the boto3 commands for doing it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The awscli ec2 describe-subnets call will actually return you the number of unused private IPv4 addresses in the subnet. The IPv4 addresses for any stopped instances are considered unavailable.

For example:

aws ec2 describe-subnets 
    --subnet-ids subnet-c0c1a23a 
    --query "Subnets[0].AvailableIpAddressCount"

Sample output:

249

To calculate the total number of usable IPs in the subnet 10.0.0.0/24 or more generally a /N:

10.0.0.0/24 => 2**(32-24) - 5
10.0.0.0/N  => 2**(32-N) - 5

Note that you subtract 5 because the first four IP addresses and the last IP address in each subnet CIDR block are reserved by AWS, and cannot be assigned to an instance.

And, for good measure, a Python script:

import boto3

ec2 = boto3.resource('ec2')

# Use this for specific subnets
# filters = [{'Name':'subnet-id', 'Values':['subnet-c0c1a23a']}]
# subnets = ec2.subnets.filter(Filters=filters)

# Use this for all subnets
subnets = ec2.subnets.all()

for subnet in list(subnets):
    free_ips = subnet.available_ip_address_count
    n = int(subnet.cidr_block.split('/')[1])
    cidr_ips = 2**(32-n)
    used_ips = cidr_ips - free_ips
    print('{:s}: cidr={:d}, aws used=5, you used={:d}, free={:d}'.
        format(subnet.id, cidr_ips, used_ips - 5, free_ips))

Sample output:

subnet-1eb2e345: cidr=256, free=251, aws used=5, you used=0
subnet-c0c1a23a: cidr=256, free=249, aws used=5, you used=2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...