Class: AwsAmiCleanup::CleanupAmis

Inherits:
Object
  • Object
show all
Defined in:
lib/aws_ami_cleanup/cleanup_amis.rb

Constant Summary collapse

DEFAULT_NUMBER_OF_AMIS_TO_KEEP =
3

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(region, number_of_amis_to_keep) ⇒ CleanupAmis

Returns a new instance of CleanupAmis.



12
13
14
15
16
17
18
19
# File 'lib/aws_ami_cleanup/cleanup_amis.rb', line 12

def initialize(region, number_of_amis_to_keep)
  @region = region

  @number_of_amis_to_keep = number_of_amis_to_keep || DEFAULT_NUMBER_OF_AMIS_TO_KEEP
  if number_of_amis_to_keep <= 0
    raise 'Number of AMIs to keep must be higher than 0.'
  end
end

Instance Attribute Details

#number_of_amis_to_keepObject

Returns the value of attribute number_of_amis_to_keep.



10
11
12
# File 'lib/aws_ami_cleanup/cleanup_amis.rb', line 10

def number_of_amis_to_keep
  @number_of_amis_to_keep
end

#regionObject

Returns the value of attribute region.



10
11
12
# File 'lib/aws_ami_cleanup/cleanup_amis.rb', line 10

def region
  @region
end

Instance Method Details

#execute!(ami_name:, ami_owner:, dry_run:) ⇒ Object



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
# File 'lib/aws_ami_cleanup/cleanup_amis.rb', line 21

def execute!(ami_name:, ami_owner:, dry_run:)
  puts "RUNNING IN DRY MODE." if dry_run

  potential_amis_to_remove = amis(ami_name, ami_owner)
  ami_ids = potential_amis_to_remove.collect(&:image_id)
  ami_ids_to_remove = ami_ids - amis_in_use
  potential_amis_to_remove.keep_if {|a| ami_ids_to_remove.include?(a.image_id) }

  if potential_amis_to_remove.count > number_of_amis_to_keep
    amis_to_remove = potential_amis_to_remove[number_of_amis_to_keep..-1]
    amis_to_keep = potential_amis_to_remove[0..(number_of_amis_to_keep-1)]

    puts "Deregistering old AMIs..."

    amis_to_remove.each do |ami|
      ebs_mappings = ami.block_device_mappings
      puts "Deregistering #{ami.image_id}"
      ami.deregister unless dry_run
      delete_ami_snapshots(ebs_mappings, dry_run)
    end

    puts "Currently active AMIs..."
    amis_to_keep.each do |ami|
      puts ami.image_id
    end
  else
    puts "no AMIs to clean."
  end
end