Created
October 2, 2015 21:53
-
-
Save martin2110/3e1a51c9e073298de7e3 to your computer and use it in GitHub Desktop.
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
class OldAmi | |
require 'aws-sdk' | |
require 'pp' | |
require 'date' | |
def initialize(days_old) | |
@images = Hash.new | |
get_regions.each do |region| | |
@old_amis = list_old_ami(region, days_old) | |
@amis_to_save = get_amis_to_save(region) | |
@amis_to_delete = @old_amis - @amis_to_save | |
@amis_to_delete.each { |ami| print_ami(ami, region) } | |
end | |
end | |
def list_old_ami(region, days_old) | |
ec2 = Aws::EC2::Client.new(region: region) | |
ec2.describe_images({ :owners => ['self'] }).images.select { |image| days_old?(image, days_old) }.map { |i| i.to_h[:image_id] } | |
end | |
def days_old?(instance, days_old) | |
instance_date = conv_date(instance.to_h[:creation_date]) | |
days = Date.today - days_old | |
begin | |
instance_date < days | |
rescue | |
nil | |
end | |
end | |
def conv_date(date_str) | |
begin | |
Date.parse(date_str) | |
rescue | |
nil | |
end | |
end | |
def get_regions | |
ec2 = Aws::EC2::Client.new(region: 'us-east-1') | |
ec2.describe_regions.to_h[:regions].map { |r| r[:region_name] } | |
end | |
def get_amis_to_save(region) | |
ec2 = Aws::AutoScaling::Client.new(region: region) | |
lc = ec2.describe_launch_configurations | |
lc.to_h[:launch_configurations].map { |image| image[:image_id] }.uniq | |
end | |
def print_ami(image, region) | |
ec2 = Aws::EC2::Resource.new(region: region) | |
ami = ec2.image(image) | |
puts "#{ami.name}, #{ami.image_id}, #{ami.creation_date}, #{region}" | |
end | |
end | |
OldAmi.new(180) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment