使用b从AWS实例获取标记

2024-04-26 23:48:42 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 实例代码name标记awsgettag代码段
3条回答

试试这样的:

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相关联的所有标记都已打印出来。

对于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)

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

相关问题 更多 >