Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining tags from AWS instances with boto

Tags:

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?

like image 618
rodolk Avatar asked Oct 22 '13 11:10

rodolk


People also ask

Where are AWS tags stored?

The tags are stored in the AWS cloud as part of your AWS account, and are private to the account. You can tag the following types of resources: EC2 instances, Amazon Machine Images (AMIs), EBS volumes, EBS snapshots, and Amazon VPC resources such as VPCs, subnets, connections, and gateways.


2 Answers

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]
like image 50
andpei Avatar answered Sep 22 '22 13:09

andpei


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.

like image 25
garnaat Avatar answered Sep 23 '22 13:09

garnaat