Obtaining tags from AWS instances with boto

ⅰ亾dé卋堺 提交于 2019-12-18 14:13:18

问题


I'm trying to obtain tags from instances in my AWS account using Python's boto library.

While this snippet works correctly bringing all tags:

    tags = e.get_all_tags()
    for tag in tags:
        print tag.name, tag.value

(e is an EC2 connection)

When I request tags from individual instances,

    print vm.__dict__['tags']

or

    print vm.tags

I'm getting an empty list (vm is actually an instance class).

The following code:

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

of course results in:

KeyError: 'Name'

My code was working until yesterday and suddenly I'm not able to get the tags from an instance.

Does anybody know whether there is a problem with AWS API?


回答1:


You have to be sure that the 'Name' tag exists before accessing it. Try this:

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)

will print:

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



回答2:


Try something like this:

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)

You should see all tags associated with instance i-xxxxxxxx printed out.




回答3:


For boto3 you will need to do this.

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)



回答4:


It turned out to be an error in my code. I did not consider the case of having one instance without the tag 'Name'.

There was one instance without the tag "Name" and my code was trying to get this tag from every instance.

When I ran this piece of code in an instance without the tag 'Name',

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

I got: KeyError: 'Name'. vm is a AWS instance. With the instances that actually had this tag set, I didn't have any problem.

Thank you for your help and sorry for asking when it was only my own mistake.



来源:https://stackoverflow.com/questions/19516678/obtaining-tags-from-aws-instances-with-boto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!