Reading EC2 tags with Boto

(Ouch! Looks like WordPress update to 3.1.3 wiped all the modifications I made to the default theme. Admittedly I should've seen that coming.) What I want to do is basically attach a key-value pair to an EC2 instance when launching it in AWS Management Console and read the value inside the instance when it's running. To be more specific, I use this to to set a key called environment that can have values like dev, stage and prod so that the Django config can decide which database to connect to etc. while starting up. I suspect that in Boto the current instance can somehow be referenced in a more direct fashion but this works as well. First, append the following to /etc/profile:
# See:
export EC2_INSTANCE_ID="`wget -q -O - || die \"wget instance-id has failed: $?\"`"
test -n "$EC2_INSTANCE_ID" || die 'cannot obtain instance-id'
export EC2_AVAIL_ZONE="`wget -q -O - || die \"wget availability-zone has failed: $?\"`"
test -n "$EC2_AVAIL_ZONE" || die 'cannot obtain availability-zone'
export EC2_REGION="`echo \"$EC2_AVAIL_ZONE\" | sed -e 's:\\([0-9][0-9]*\\)[a-z]*\\$:\\\\1:'`"
Now we know the region and instance ID. Next, install Boto by running the following commands:
wget ""
zcat boto-2.0b4.tar.gz | tar xfv -
cd boto-2.0b4
python ./ install
Then, add these lines to ~/.profile:
Or the equivalent in ~/.boto:
aws_access_key_id = <ACCESS_KEY>
aws_secret_access_key = <SECRET_KEY>
Now, to read the tag we want in Python:
#!/usr/bin/env python                                                                                                                                           

import os
from boto import ec2

ec2_instance_id = os.environ.get('EC2_INSTANCE_ID')
ec2_region = os.environ.get('EC2_REGION')

conn = ec2.connect_to_region(ec2_region)

reservations = conn.get_all_instances()
instances = [i for r in reservations for i in r.instances]

for instance in instances:
    if instance.__dict__['id'] == ec2_instance_id:
        print instance.__dict__['tags']['environment']

Tagged with:

Categorised as: