检查是否为所有EC2 AWS实例启用了终止

时间:2018-09-25 12:43:00

标签: amazon-web-services amazon-ec2

我有一个列出所有区域中所有ec2实例的代码

import boto3



client = boto3.client('ec2',region_name='us-east-1')

ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]

for region in ec2_regions:
    conn = boto3.resource('ec2',region_name=region)
    instances = conn.instances.filter()
    for instance in instances:
        #if instance.state["Name"] == "running":
     print instance.id #   , instance.instance_type, region)

现在,我要针对所有实例检查是否启用了终止保护

terminate_protection=client.describe_instance_attribute(InstanceId =instance.id,Attribute = 'disableApiTermination')

上面的代码仅列出了us-east-1的实例,如果传递的instanceID不是该区域的实例,则会抱怨(找不到实例)

如何将instanceID传递给describe_instance_attribute

1 个答案:

答案 0 :(得分:1)

您已将创建为client的boto3客户端对象本地化到us-east-1区域,因为这是您使用region_name参数指定的对象。您需要为每个区域创建一个单独的客户端:

client = boto3.client('ec2')  # Doesn't actually matter what region you use here
ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]

for region in ec2_regions:
    # Need to create a new client per-region
    client = boto3.client('ec2', region_name=region)
    conn = boto3.resource('ec2',region_name=region)
    instances = conn.instances.filter()
    for instance in instances:
        print instance.id #   , instance.instance_type, region)
        # Now we can get the termination state
        terminate_protection=client.describe_instance_attribute(InstanceId =instance.id,Attribute = 'disableApiTermination')