Need to release all those elastic IP that are unassociated using boto3 in All regions

爷,独闯天下 提交于 2020-12-13 05:45:23

问题


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

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

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


回答1:


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

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

You can use:

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)




来源:https://stackoverflow.com/questions/57597389/need-to-release-all-those-elastic-ip-that-are-unassociated-using-boto3-in-all-re

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!