需要释放所有区域中所有未使用boto3关联的弹性IP [英] Need to release all those elastic IP that are unassociated using boto3 in All regions

查看:277
本文介绍了需要释放所有区域中所有未使用boto3关联的弹性IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用boto3和lamda释放未使用的弹性IP.在这里,我需要释放在我的AWS账户的所有区域中存在的所有IP.

I am using boto3 along with lamda to release the unused elastic IPs. Here I need to release all those IPs present in all regions of My AWS account.

def elastic_ips_cleanup():
    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'])

我使用了上面的代码,但是它仅在执行lambda函数的特定区域中释放IP.

I used the above codes however it only releases the IP in a particular region where I am executing the lambda function.

预期输出:它应该释放所有区域中存在的所有未使用的弹性IP.

The expected output: It should release all the unused Elastic IPs present in all the Regions.

推荐答案

初始化的 boto3.client 仅在特定区域有效.默认情况下,您在 .aws/config

Once initialized boto3.client works only in specific region. By default the one you have in your .aws/config

您可以遍历区域并通过可选参数 region_name = REGION_NAME 用特定区域重新初始化客户端.显然,然后重新运行您的函数.

You can loop through regions and reinitilize the client with specific region passing optional argument region_name=REGION_NAME. Then rerun yuor function, apparently.

您可以使用:

import boto3
import logging

def elastic_ips_cleanup(region):
    client = boto3.client('ec2', region_name=region)
    # The rest of code you said you have tested already...


regions = [r['RegionName'] for r in boto3.client('ec2').describe_regions()['Regions']]

for region in regions:
    logging.info(f"Cleaning {region}")
    elastic_ips_cleanup(region)


这篇关于需要释放所有区域中所有未使用boto3关联的弹性IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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