Class: Awsclean::AmiClean

Inherits:
AwsCommand show all
Defined in:
lib/awsclean/ami_clean.rb

Constant Summary collapse

SERVICE_IDENTIFIER =
"EC2"
IMAGE_LIST_HEADER =
['REGION', 'IN USE?', 'NAME', 'AMI ID', 'CREATED', 'ELEGIBLE FOR CLEANUP?']
IMAGE_LIST_FORMAT =
'%-10s%-10s%-24s%-24s%-42s%-6s'

Class Method Summary collapse

Methods inherited from AwsCommand

filter_regions, supported_regions

Class Method Details

.run(options) ⇒ Object


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/awsclean/ami_clean.rb', line 12

def self.run options
  regions = filter_regions(options[:r])

  if regions.empty?
    puts "Please specify region with -r [regions, e.g., 'all' or 'us-west-1,us-east-1']"
    exit 1
  end

  regions.each do |region|
    puts "[clean_amis] checking region: #{region}"

    ec2 = Aws::EC2::Client.new(region: region)

    # Get a list of all AMIs in use.
    #
    res = ec2.describe_instances(
      filters: [{ name: 'instance-state-name', values: %w(running) }],
      max_results: 1000
    )
    instances   = res.reservations.flat_map(&:instances)
    amis_in_use = instances.map(&:image_id).uniq

    # Allow user to define a list of locked AMIs
    if !options[:a].empty?
      options[:a].each do |ami|
        puts "Locked AMI: #{ami}"
        amis_in_use << ami
      end
    end

    # Get a list of all of AMI's owned by the account.
    #
    res = ec2.describe_images(owners: %w(self))
    images = res.images

    images.each do |image|
      image.in_use = amis_in_use.include?(image.image_id)
      image.elegible_for_cleanup = (image.stale?(options[:e]) && !image.in_use)
    end

    # We always show a list of images
    #
    puts build_image_list_header
    images.each { |image| puts build_image_list_entry(region, image) }

    if options[:c]
      images.select(&:elegible_for_cleanup).each do |image|
        puts "[#{region}] Deregistering image: #{image.image_id} #{image.creation_date}"
        ec2.deregister_image(image_id: image.image_id)

        image.block_device_mappings.each { |bdm|
          puts "[#{region}] Deregistering image #{image.image_id}: deleting snapshot #{bdm.ebs.snapshot_id}..."
          ec2.delete_snapshot(snapshot_id: bdm.ebs.snapshot_id)
        }
        puts "[#{region}] Deregister image complete: #{image.image_id}"
      end
    end
  end
end