使用boto从AWS实例获取标记

rod*_*olk 18 python instances boto amazon-web-services

我正在尝试使用Python的boto库从我的AWS账户中的实例获取标签.

虽然此代码段可以正常使用所有代码:

    tags = e.get_all_tags()
    for tag in tags:
        print tag.name, tag.value
Run Code Online (Sandbox Code Playgroud)

(e是EC2连接)

当我从各个实例请求标签时,

    print vm.__dict__['tags']
Run Code Online (Sandbox Code Playgroud)

要么

    print vm.tags
Run Code Online (Sandbox Code Playgroud)

我得到一个空列表(vm实际上是一个实例类).

以下代码:

    vm.__dict__['tags']['Name']
Run Code Online (Sandbox Code Playgroud)

当然导致:

KeyError: 'Name'
Run Code Online (Sandbox Code Playgroud)

我的代码一直工作到昨天,突然间我无法从实例中获取标签.

有人知道AWS API是否存在问题?

and*_*pei 32

在访问之前,您必须确保"Name"标记存在.试试这个:

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)
Run Code Online (Sandbox Code Playgroud)

将打印:

i-4e444444 [stopped]
Amazon Linux (i-4e333333) [running]
Run Code Online (Sandbox Code Playgroud)