如何计算AWS中子网的总ip

问题描述 投票:-1回答:1

最近,由于ENI消耗了大量的IP,我们在VPC中遇到了IP问题。我需要在boto3中编写一个脚本,以便在总ip使用率增加80%左右时触发警报。

因此,我需要知道VPC中子网中分配的总IP。我需要使用的IP和免费IP的总数。

请分享boto3命令。

amazon-web-services subnet
1个回答
1
投票

awscli ec2 describe-subnets调用实际上会返回子网中未使用的私有IPv4地址的数量。任何已停止的实例的IPv4地址都被视为不可用。

例如:

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

样本输出:

249

要计算子网10.0.0.0/24中的可用IP总数或更多a / N:

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

请注意,您减去5,因为前四个IP地址和每个子网CIDR块中的最后一个IP地址是reserved by AWS,并且无法分配给实例。

并且,为了更好地衡量,Python脚本:

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))

样本输出:

subnet-1eb2e345: cidr=256, free=251, aws used=5, you used=0
subnet-c0c1a23a: cidr=256, free=249, aws used=5, you used=2
© www.soinside.com 2019 - 2024. All rights reserved.