Created
March 27, 2014 19:32
-
-
Save conarro/9816219 to your computer and use it in GitHub Desktop.
AWS EC2 Inventory script
This file contains hidden or 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/ruby | |
require 'dotenv' | |
require 'aws' | |
require 'csv' | |
# patch instance to return runtime | |
class AWS::EC2::Instance | |
def runtime | |
@runtime ||= Time.now - launch_time | |
end | |
end | |
# load .env into ENV | |
Dotenv.load | |
output_file = ARGV[0] || 'output.csv' | |
puts "Starting inventory, output will be saved to #{output_file}" | |
# get ec2 client - assumes AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are in ENV | |
ec2 = AWS::EC2.new | |
region_fields = ['name', 'endpoint'] | |
instance_fields = ['availability_zone', 'id', 'ip_address', 'instance_type', 'status', 'runtime', 'launch_time', 'key_name', 'image_id'] | |
headers = region_fields.map {|field| "region_#{field}"}.concat(instance_fields).flatten | |
rows = [] | |
# go through all regions and instances and store row data | |
ec2.regions.each do |region| | |
puts "Taking inventory of #{region.name}..." | |
region_data = region_fields.map {|field| region.send(field) } | |
ec2.regions["#{region.name}"].instances.each do |i| | |
rows << instance_fields.map { |field| i.send(field) }.unshift(region_data).flatten | |
end | |
end | |
# output to csv | |
puts "Saving inventory to #{output_file}" | |
CSV.open(output_file, "w") do |csv| | |
csv << headers | |
rows.each { |row| csv << row } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment