需要在所有区域释放所有使用 boto3 未关联的弹性 IP
Need to release all those elastic IP that are unassociated using boto3 in All regions
我正在使用 boto3 和 lamda 来释放未使用的弹性 IP。在这里,我需要释放我的 AWS 账户所有区域中存在的所有 IP。
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。
预期输出:它应该释放所有区域中存在的所有未使用的弹性 IP。
初始化后boto3.client
仅在特定区域有效。默认情况下,您 .aws/config
中的那个
您可以遍历区域并使用传递可选参数的特定区域重新初始化客户端 region_name=REGION_NAME
。然后重新运行你的功能,显然。
您可以使用:
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 和 lamda 来释放未使用的弹性 IP。在这里,我需要释放我的 AWS 账户所有区域中存在的所有 IP。
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。
预期输出:它应该释放所有区域中存在的所有未使用的弹性 IP。
初始化后boto3.client
仅在特定区域有效。默认情况下,您 .aws/config
您可以遍历区域并使用传递可选参数的特定区域重新初始化客户端 region_name=REGION_NAME
。然后重新运行你的功能,显然。
您可以使用:
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)