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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…