【问题标题】:Boto3: Get EC2 images owned by meBoto3:获取我拥有的 EC2 映像
【发布时间】:2017-03-05 21:53:45
【问题描述】:
我想获取我拥有的所有 ami 图片。我尝试了以下方法:
ec2 = boto3.resource('ec2')
owner_id = 'owner_id'
filters = [{'Name': 'owner-id', 'Values': [owner_id]}]
images = ec2.images.filter(Filters=filters).all()
但我需要将 owner_id explicid 放入代码中。是否有任何解决方案可以从 aws 凭据自动执行此操作?
【问题讨论】:
标签:
amazon-web-services
amazon-ec2
boto3
amazon-ami
【解决方案1】:
您可以使用 STS API 来获取此信息。
我发现这篇文章在谈论它:getting the current user account-id in boto3
所以你需要的代码是:
ec2 = boto3.resource('ec2', region_name='us-east-1')
owner_id = boto3.client('sts').get_caller_identity().get('Account')
filters = [{'Name': 'owner-id', 'Values': [owner_id]}]
images = ec2.images.filter(Filters=filters).all()
确保将区域名称更改为正确的名称,如果您已在环境中的其他地方设置了它,则将其省略。
【解决方案2】:
您应该能够将 self 用作所有者。这是我用的。
boto3conn = boto3.resource("ec2", region_name="us-west-2")
images = boto3conn.images.filter(Owners=['self'])
【解决方案3】:
这会有所帮助,它将向您显示所有 AMI 那是 owned your aws account
import boto3
client = boto3.client('ec2', region_name='us-east-1')
response = client.describe_images(Owners=['self'])
for ami in response['Images']:
print (ami['ImageId'])
【讨论】:
-
虽然此代码可能会回答问题,但提供有关其解决问题的方式和/或原因的附加上下文将提高答案的长期价值。Read this。