#!/usr/local/ruby-current/bin/ruby # Copyright:: Copyright (c) 2014 eGlobalTech, Inc., all rights reserved # # Licensed under the BSD-3 license (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License in the root of the project or at # # http://egt-labs.com/mu/LICENSE.html # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'optimist' require 'json' require File.realpath(File.expand_path(File.dirname(__FILE__)+"/../bin/mu-load-config.rb")) require 'mu' $opts = Optimist::options do banner <<-EOS #{$0} [-c credentials] [-i imagename] EOS opt :credentials, "Use these AWS credentials from mu.yaml instead of the default set", :required => false, :type => :string opt :image, "Purge a specific image, instead of just scrubbing old ones", :required => false, :type => :string end filters = [ { name: "owner-id", values: [MU::Cloud::AWS.credToAcct($opts[:credentials])] } ] in_use = MU::Cloud.getStockImage("AWS").values.flatten.map { |h| h.values }.flatten MU::Cloud::AWS.listRegions.each { | r| images = MU::Cloud::AWS.ec2(region: r, credentials: $opts[:credentials]).describe_images( filters: filters + [{ "name" => "state", "values" => ["available"]}] ).images images.each { |ami| next if in_use.include?(ami) if ($opts[:image] and ami.name == $opts[:image]) or ((DateTime.now.to_time - DateTime.parse(ami.creation_date).to_time) > 15552000 and ami.name.match(/^MU-(PROD|DEV)/)) snaps = [] ami.block_device_mappings.each { |dev| if !dev.ebs.nil? snaps << dev.ebs.snapshot_id end } MU.log "Deregistering #{ami.name}, #{r} (#{ami.creation_date})", MU::WARN, details: snaps begin MU::Cloud::AWS.ec2(region: r, credentials: $opts[:credentials]).deregister_image(image_id: ami.image_id) rescue Aws::EC2::Errors::InvalidAMIIDUnavailable end snaps.each { |snap_id| begin MU::Cloud::AWS.ec2(region: r, credentials: $opts[:credentials]).delete_snapshot(snapshot_id: snap_id) rescue Aws::EC2::Errors::InvalidSnapshotInUse sleep 5 retry rescue Aws::EC2::Errors::InvalidSnapshotNotFound end } end } }