我正在尝试使用 Python 的 boto 库从我的 AWS 账户中的实例获取标签。
虽然此代码段可以正常工作,但会带来所有标签:
tags = e.get_all_tags()
for tag in tags:
print tag.name, tag.value
(e 是 EC2 连接)
当我从单个实例请求标签时,
print vm.__dict__['tags']
或
print vm.tags
我得到一个空列表(vm 实际上是一个实例类)。
以下代码:
vm.__dict__['tags']['Name']
当然会导致:
KeyError: 'Name'
我的代码一直工作到昨天,突然我无法从实例中获取标签。
有人知道AWS API是否有问题吗?
最佳答案
在访问它之前,您必须确保存在“名称”标签。试试这个:
import boto.ec2
conn=boto.ec2.connect_to_region("eu-west-1")
reservations = conn.get_all_instances()
for res in reservations:
for inst in res.instances:
if 'Name' in inst.tags:
print "%s (%s) [%s]" % (inst.tags['Name'], inst.id, inst.state)
else:
print "%s [%s]" % (inst.id, inst.state)
将打印:
i-4e444444 [stopped]
Amazon Linux (i-4e333333) [running]
关于python - 使用 boto 从 AWS 实例获取标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19516678/