python - 使用 boto 从 AWS 实例获取标签

标签 python amazon-web-services boto instances

我正在尝试使用 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/

相关文章:

python - tensorflow 错误 : Shape must be rank 0 but is rank 1 for 'cond_1/Switch'

python - Boto (Python)-反转的遗愿 list

python - 在python中将包装为字符串的元组转换为元组的简单方法

python - Paramiko 下载、处理并重新上传同一文件

java - 谷歌应用引擎的OSS实现?

python - 如何更改存储桶的 amazon aws S3 时区设置

python - S3 上的 Django collectstatic 每次在 Heroku 上上传未更改的文件

node.js - 如何在 Node js 中验证 Cognito 用户池

tomcat - 在 Amazons Elastic Beanstalk 上部署 WAR

linux - 使用云形成在 linux-Ec2 实例中自动挂载 ebs 卷?