Skip to content

Instantly share code, notes, and snippets.

@dtenenba
Last active October 22, 2015 23:19
Show Gist options
  • Save dtenenba/f1a63e5aff6e97aa8597 to your computer and use it in GitHub Desktop.
Save dtenenba/f1a63e5aff6e97aa8597 to your computer and use it in GitHub Desktop.
require 'aws-sdk'
require 'time'
require 'yaml'
require 'httparty'
Aws.config.update({region: 'us-east-1', credentials: Aws::Credentials.new('access_key', 'secret_key')})
ec2 = Aws::EC2::Client.new(region: 'us-east-1')
def get_amis(ec2)
amis = ec2.describe_images({owners: ['self']}).images
amis.sort{|a,b| Time.parse(a.creation_date) <=> Time.parse(b.creation_date) }
end
def get_removables(ec2)
snaps = ec2.describe_snapshots({owner_ids: ['self']}).snapshots
vols = ec2.describe_volumes.volumes
amis = ec2.describe_images({owners: ['self']}).images
# snapshot ids mentioned in amis
ami_snaps = amis.map do |ami|
ami.block_device_mappings.map do |bdm|
unless bdm.ebs.respond_to? :snapshot_id
1
else
bdm.ebs.snapshot_id
end
end
end
ami_snaps = ami_snaps.flatten.find_all{|i| i != 1}
vol_snaps = vols.map{|i| i.snapshot_id}
snap_ids = snaps.map{|i|i.snapshot_id}
removeme = snap_ids - ami_snaps
removeme = removeme - vol_snaps
removeme
end
def get_bioc_amis
yaml_str = HTTParty.get("http://master.bioconductor.org/config.yaml")
yaml = YAML::load(yaml_str)
yaml["ami_ids"].values
end
def rmami(ec2, ami_id)
bioc_amis = get_bioc_amis()
running_amis = get_running_amis(ec2)
if bioc_amis.include? ami_id
puts "#{ami_id} is in bioc_amis! Not deleting it."
return
end
if running_amis.include? ami_id
puts "#{ami_id} is in running_amis! Not deleting it."
return
end
puts "deleting #{ami_id}"
ec2.deregister_image({image_id: ami_id})
end
def rmsnap(ec2, snap_id)
ec2.delete_snapshot({snapshot_id: snap_id})
end
def get_running_amis(ec2)
instances = ec2.describe_instances
instances.reservations.map{|i| i.instances.first.image_id}
end
# workflow:
# log in
# amis = get_amis ec2
# if one looks removable, try
# rmami(ec2, amis[x].image_id) # where x is the candidate
# if that works, then wait a sec and do:
# get_removables(ec2) # returns removable snapshots
# ...review them and if all is ok
# ...and the one to remove is first in the array:
# rmsnap(ec2, get_removables(ec2).first)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment