-
-
Save darkseed/987370 to your computer and use it in GitHub Desktop.
SSH into an EC2 instance by name.
This file contains 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
#!/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