如何使用 python 查找 AMI 的 AWS 区域?

How to find AWS region of AMI with python?

我正在尝试在 Amazon Web Services 中为 ami 找到一个区域,在那里我只知道 ami id,最好是 python。怎么做?

这是片段

import boto3

ami_id = "HERE IS YOUR AMI ID"

client = boto3.client('ec2')
ec2 = boto3.resource('ec2')

regions = client.describe_regions()
for region in regions["Regions"]:
    region_name = region["RegionName"]
    print(region_name)
    try:
        image = ec2.Image(ami_id)
        response = image.describe_attribute(Attribute='description')
        print("Found ami in region {}".format(region_name))
        break
    except: 
        print("Ami doesnt exist in {} region".format(region_name))
for image_id in ['image_id_1', 'image_id_2', ...]:
    for region in regions:
        ec2 = boto3.resource('ec2', region_name = region)
        try:
            response = ec2.images.filter(ImageIds=[image_id])
            print(region, list(response)[0].name)
        except botocore.exceptions.ClientError as exc:
            if 'InvalidAMIID.NotFound' in str(exc):
                pass
            else:
                raise exc