Skip to content

Instantly share code, notes, and snippets.

@ishikuro ishikuro/ec2ls
Last active Oct 11, 2019

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('lhr:', 'profile:default', 'help')
if params['h'] or params['help'] then
puts "\e[31mUsage: ec2ls [-r region] [--profile profile]'\e[0m"
abort
end
class Object
def name_tag
self.tags.select{|t| t.key == 'Name'}.first[:value] rescue "\e[34mNoName\e[0m"
end
end
# Fetch instance status
Aws.config[:profile] = params['profile']
ec2 = Aws::EC2::Client.new()
region = [params['r'], ec2.config[:region], 'us-east-1'].reject{|i| i.to_s.empty?}.first
instances = Aws::EC2::Resource.new(region: region).instances()
vpcs = ec2.describe_vpcs().vpcs.map{|vpc| [vpc.vpc_id, vpc.name_tag] }.to_h
subnets = ec2.describe_subnets().subnets.map{|subnet| [subnet.subnet_id, name: subnet.name_tag, cidr: subnet.cidr_block] }.to_h
# Render
puts instances.map{|instance|
[
instance.id,
instance.state.name.gsub(/running/, "\e[32mrunning\e[0m").gsub(/stopped/, "\e[31mstopped\e[0m"),
ec2.describe_images({ image_ids: [instance.image_id] }).images.first.name[0..5] + '#',
instance.name_tag,
"#{vpcs[instance.vpc_id]}/#{subnets[instance.subnet_id][:name]}(#{subnets[instance.subnet_id][:cidr]})",
]
}.sort_by{|line| line[-1]}.map{|line|
line.delete_at(-1) unless params['l']
line.join("\t")
}.join("\n")
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.