Skip to content

Instantly share code, notes, and snippets.

@ishikuro

ishikuro/ec2ssh

Last active Dec 22, 2018
Embed
What would you like to do?
#!/usr/bin/env ruby
require 'aws-sdk'
require 'optparse'
require 'uri'
# Parse params and args
params = ARGV.getopts('ql:i:r:p:', 'profile:default', 'dry-run')
target, command = ARGV.permute!
unless target then
puts <<-END
\e[31mUsage:
ec2ssh.rb <tag:Name> # will fetch <tag:User> as username
ec2ssh.rb -l ec2-user -i ./my.pem -r ap-northeast-1 <tag:Name>\e[0m
END
abort
end
uri = URI.parse "ssh://#{target}"
# Fetch instance status
Aws.config[:profile] = params['profile']
region = [params['r'], Aws::EC2::Client.new().config[:region], 'us-east-1'].reject{|i| i.to_s.empty?}.first
instance = uri.host.start_with?('i-') ?
Aws::EC2::Resource.new(region: region).instance(uri.host)
:
Aws::EC2::Resource.new(region: region).instances({filters: [{name: 'tag:Name', values: [uri.host]}]}).first
unless instance then
puts "\e[31mError\e[0m: The instance Name:#{target} does not exist on #{region} or your account."
abort
end
unless instance.state.name == 'running' then
puts "\e[31mError\e[0m: #{instance.id} is not running."
abort
end
# Build ssh command
identity_option = params['i'] ? "-i #{params['i']}" : ''
port = [uri.port, params['p'], 22].reject{|i| i.to_s.empty?}.first
default_user = instance.tags.select{|e| e[:key] == 'User'}.first[:value] rescue 'ec2-user'
user = [uri.userinfo, params['l'], default_user].reject{|i| i.to_s.empty?}.first
host = instance.public_ip_address
ssh = "ssh #{identity_option} -p #{port} #{user}@#{host} #{command}"
# Verbose mode
unless params['q'] then
groups = instance.security_groups.map{|e| e[:group_id]}.join(',')
puts <<-END
If you cannot see the login prompt, check security groups by
\e[36mhttps://#{region}.console.aws.amazon.com/ec2/v2/home?region=#{region}#SecurityGroups:groupId=#{groups};sort=groupId\e[0m
⚡️ #{ssh}
END
end
exec ssh unless params['dry-run']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.