我正在使用boto3,我需要列出所有弹性IP,找到与任何实例无关的IP并释放它们。
我在做的是:
import boto3
ec2 = boto3.resource('ec2')
然后我可以列出所有卷:
for volume in ec2.volumes.all():
或者像这样的所有实例:
for instance in ec2.instances.all():
但我不知道如何列出所有弹性IP。
boto3文档列出了对象ClassicAddress,这是我发布IP所需的内容。
http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#classicaddress
但是,我不知道如何获得所有ClassicAddresses的集合
我们可以检查EIP是否有与之关联的eni。这样,它将克服EIP是否与NAT或EC2相关联的问题。
只需使用mkreder的代码并进行小的更改来检查NetworkInterfaceId而不是InstanceId
import boto3
client = boto3.client('ec2')
addresses_dict = client.describe_addresses()
for eip_dict in addresses_dict['Addresses']:
if "NetworkInterfaceId" not in eip_dict:
print(eip_dict['PublicIp'])
client.release_address(AllocationId=eip_dict['AllocationId'])
无论EIP是与NAT还是EC2相关联,它都会附加网络接口,但是当连接到NAT时它没有InstanceId。
我得到了这个代码:
def elastic_ips_cleanup():
""" Cleanup elastic IPs that are not being used """
client = boto3.client('ec2')
addresses_dict = client.describe_addresses()
for eip_dict in addresses_dict['Addresses']:
if "InstanceId" not in eip_dict:
print (eip_dict['PublicIp'] +
" doesn't have any instances associated, releasing")
client.release_address(AllocationId=eip_dict['AllocationId'])
用过的:
if "InstanceId" not in eip_dict:
if "NetworkInterfaceId" not in eip_dict:
我不会使用mkreder的代码,因为它可以释放实际上没有附加到实例的EIP,也可以释放附加到VPC中的NAT网关的EIP。希望我使用运行此代码
DryRun = True