Skip to content

Instantly share code, notes, and snippets.

@darkseed
Forked from qwzybug/ec2-ssh.rb
Created May 23, 2011 19:30
Show Gist options
  • Save darkseed/987370 to your computer and use it in GitHub Desktop.
Save darkseed/987370 to your computer and use it in GitHub Desktop.
SSH into an EC2 instance by name.
#!/usr/bin/env ruby
instance_name = ARGV[0]
abort "Please specify an instance name" unless instance_name and instance_name.length > 0
instance_info, selected_instance = {}, nil
info_keymap = {2 => :ami_id, 3 => :address, 5 => :status, 6 => :keypair_name}
instances = `ec2-describe-instances`.split("\n").map{|l| l.split("\t")}
instances.each do |line|
case line.first
when 'INSTANCE'
keys = info_keymap.keys
instance_id = line[1]
this_instance = Hash[*info_keymap.values_at(*keys).zip(line.values_at(*keys)).flatten]
instance_info[instance_id] = this_instance
when 'TAG'
if line[1] == 'instance' and line[3] == 'Name'
selected_instance = line[2] if line[4] == instance_name
end
end
end
abort "No instance named #{instance_name}!" unless selected_instance
instance = instance_info[selected_instance]
abort "Instance is not running!" unless instance[:status] == 'running'
instance_address = instance[:address]
keypair_name = instance[:keypair_name]
ec2_home = `echo $EC2_HOME`.chomp
keyfile = "#{ec2_home}/#{keypair_name}.pem"
abort "No private key matching '#{keypair_name}' found in #{ec2_home}!" unless File.exists? keyfile
exec "ssh -i #{keyfile} -l ec2-user #{instance_address}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment