Created
October 17, 2011 16:55
-
-
Save robballou/1293067 to your computer and use it in GitHub Desktop.
Get the EC2 instance name
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Get the EC2 instance name (tag "Name") for the instance | |
Usage: | |
python instance_name.py [instance id] | |
On an EC2 instance, you can run: | |
python instance_name.py `ec2metadata --instance-id` | |
You'll need the boto library and your connection environment variables setup for this to work! | |
""" | |
import sys | |
from boto.ec2.connection import EC2Connection | |
if len(sys.argv) != 2: | |
print "Please provide instance ID" | |
sys.exit(1) | |
c = EC2Connection() | |
r = c.get_all_instances([sys.argv[1],]) | |
try: | |
print r[0].instances[0].tags['Name'] | |
except: | |
sys.exit(1) |
If you want to iterate through all instances in all reservations you can loop through it like so:
import boto
conn = boto.connect_ec2(key,secret)
reservations = conn.get_all_reservations()
for r in reservations
print r.instances[0].tags['Name']
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
that doesnt work very well in the multitude of cases where your instance is not r[0].instances[0].