Skip to content

Instantly share code, notes, and snippets.

@jbiel
Created May 3, 2012 19:47
Show Gist options
  • Select an option

  • Save jbiel/2588762 to your computer and use it in GitHub Desktop.

Select an option

Save jbiel/2588762 to your computer and use it in GitHub Desktop.
ec2 connect tool
---
dev:
access_key_id:
secret_access_key:
prod:
access_key_id:
secret_access_key:
qa:
access_key_id:
secret_access_key:
#!/usr/bin/env python
from boto.ec2.connection import EC2Connection
from os import system
import os
import sys
import yaml
f = open(os.getenv('HOME') + '/.aws-credentials')
keys = yaml.load(f)
f.close()
runmode = sys.argv[1]
print "Runmode: " + runmode
print ""
conn = EC2Connection(keys[runmode]['access_key_id'], keys[runmode]['secret_access_key'])
instances = conn.get_all_instances()
running_instances = []
index = 1
for r in instances:
for inst in r.instances:
if inst.state == 'running':
running_instances.append({'instance_id': inst.id, 'public_hostname': inst.public_dns_name, 'tag_name': inst.tags.get('Name', '---'), 'local_hostname': inst.private_dns_name, 'index': index})
index += 1
instance_index = dict((p['index'], i) for i, p in enumerate(running_instances))
running_instances_sorted = sorted(running_instances, key=lambda k: k['index'])
def isodd(num):
return num & 1 and True or False
fmt="%2s %-10s %-10s %-43s"
print fmt % ("","Instance","Name","Public Hostname")
print ""
for inst in running_instances_sorted:
if isodd(inst['index']):
print "\033[34m" + fmt % (inst['index'],inst['instance_id'],inst['tag_name'],inst['public_hostname'])
else:
print "\033[32m" + fmt % (inst['index'],inst['instance_id'],inst['tag_name'],inst['public_hostname'])
print "\033[0m"
var = raw_input("Enter ID: ")
hostname = running_instances[instance_index.get(int(var), -1)]['public_hostname']
instance_name = running_instances[instance_index.get(int(var), -1)]['tag_name']
print "Connecting to " + runmode + " " + instance_name
system("ssh " + hostname)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment