如何在AWS中计算子网的总IP [英] How to calculate total ip's of a subnet in AWS

查看:85
本文介绍了如何在AWS中计算子网的总IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,由于ENI占用了大量IP,VPC中出现了IP用尽的问题.我需要在boto3中编写一个脚本,以在总IP使用量增加大约80%左右时触发警报.

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.

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

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.

请分享boto3命令.

Please share the boto3 commands for doing it.

推荐答案

awscli ec2 描述子网调用实际上将为您返回子网中未使用的专用IPv4地址的数量.任何停止的实例的IPv4地址都被视为不可用.

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.

例如:

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

示例输出:

249

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

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

请注意,您减去5是因为每个子网CIDR块中的前四个IP地址和最后一个IP地址是

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.

在很大程度上,它是一个Python脚本:

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

示例输出:

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

这篇关于如何在AWS中计算子网的总IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆