Skip to content

Instantly share code, notes, and snippets.

@sumikawa
Last active February 1, 2019 01:31
Show Gist options
  • Save sumikawa/7116852 to your computer and use it in GitHub Desktop.
Save sumikawa/7116852 to your computer and use it in GitHub Desktop.
ssh to ec2 by instance name
#!/usr/bin/env ruby
require 'optparse'
m = /((?<user>[\w-]+)@)?((?<instance>i-[\w]+)|(?<name>[\w]+))/.match(ARGV.pop)
user = m[:user] || "ec2-user"
if m[:instance]
dnsname = `aws ec2 describe-instances --instance-ids #{m[:instance]} | jq -r '.Reservations[].Instances[].NetworkInterfaces[].Association.PublicDnsName' | grep -v null | tail -1`
end
if dnsname.nil? || dnsname.empty?
puts "No such instance"
exit
end
puts "Connecting to #{dnsname}"
exec "ssh #{ARGV.join(' ')} #{user}@#{dnsname}"
## TODO
# ssh by Name Tag like ec2ssh
# support scp
# specify region
# check cache first and reget instances when cache didn't hit
# Support EIP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment