使用boto从AWS实例获取标签

21
我正在尝试使用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 是否有问题吗?


1
你说“vm”是一个“实例类”。我不确定这是什么意思。你可以输入“type(vm)”并在此处发布结果吗? - garnaat
抱歉误导了您。在boto中,有一个名为“instance”的类,代表着AWS实例。 - rodolk
4个回答

36

在访问“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)

会被打印出来:

i-4e444444 [stopped]
Amazon Linux (i-4e333333) [running]

Boto现在具有直接获取实例的功能 -- instances = self._ec2_connection.get_only_instances() -- http://boto.cloudhackers.com/en/latest/ref/ec2.html#boto.ec2.connection.EC2Connection.get_only_instances - storm_m2138
我认为这个答案可以更清晰易懂地表达。它是类似问题的最接近答案,在阅读了半打次之后,我仍然对标签的工作原理感到困惑。 - jorfus

4
尝试使用类似以下的代码:

像这样尝试一下:

import boto.ec2

conn = boto.ec2.connect_to_region('us-west-2')
# Find a specific instance, returns a list of Reservation objects
reservations = conn.get_all_instances(instance_ids=['i-xxxxxxxx'])
# Find the Instance object inside the reservation
instance = reservations[0].instances[0]
print(instance.tags)

您应该看到打印出与实例 i-xxxxxxxx 相关的所有标签。


这是我做的。我获取了预订列表,然后获取了预订中实例的列表。当我打印标签时,我看到一个空列表“{}”。奇怪的是,我在另一个AWS帐户上运行相同的代码,可以看到实例的所有标签。这似乎是我的第一个AWS帐户的问题。 - rodolk
事实证明这是我的代码错误。有一个例子没有标记“名称”,我的代码尝试从每个例子中获取此标记。因此我得到了:KeyError:“Name”。谢谢您的帮助。 - rodolk
1
目前是:conn.get_all_instances(instance_ids=['i-xxxx']) 相比之下:conn.get_all_instances(instance_id=['i-xxxx']) 参数需要是复数形式。 - Munhitsu

1
对于boto3,您需要执行以下操作。
import boto3
ec2 = boto3.resource('ec2')
vpc = ec2.Vpc('<your vpc id goes here>')
instance_iterator = vpc.instances.all()

for instance in instance_iterator:
    for tag in instance.tags:
        print('Found instance id: ' + instance.id + '\ntag: ' + tag)

如何获取不在VPC中的公共IP标签? - user5760871
文档在这里:https://boto3.readthedocs.io/en/latest/reference/services/ec2.html 您可能需要类似ClassicAddress的东西。 - nu everest

0

原来是我的代码出了错误。我没有考虑到没有“名称”标签的情况。

有一个实例没有“名称”标签,而我的代码却试图从每个实例中获取此标签。

当我在一个没有“名称”标签的实例中运行这段代码时,

vm.__dict__['tags']['Name']

我得到了一个KeyError: 'Name'。vm是一个AWS实例。对于那些实际上设置了这个标签的实例,我没有任何问题。

感谢您的帮助,很抱歉在只有我的错误时提出了问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接