Skip to content

Instantly share code, notes, and snippets.

@robballou
Created October 17, 2011 16:55
Show Gist options
  • Save robballou/1293067 to your computer and use it in GitHub Desktop.
Save robballou/1293067 to your computer and use it in GitHub Desktop.
Get the EC2 instance name
"""
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)
@mattghali
Copy link

that doesnt work very well in the multitude of cases where your instance is not r[0].instances[0].

@goshlanguage
Copy link

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