Class: Awsclean::EcrClean

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

Constant Summary collapse

SERVICE_IDENTIFIER =
"ECR"
IMAGE_LIST_HEADER =
[
  'REGION', 'IN USE?', 'REPOSITORY URI', 'TAGS',
  'IMAGE ID', 'CREATED', 'SIZE', 'ELEGIBLE FOR CLEANUP?'
]
IMAGE_LIST_FORMAT =
'%-16s%-12s%-64s%-24s%-24s%-42s%-12s%-24s'

Class Method Summary collapse

Methods inherited from AwsCommand

filter_regions, supported_regions

Class Method Details

.run(options) ⇒ Object



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
# File 'lib/awsclean/ecr_clean.rb', line 15

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_ecr_images] Checking region: #{region}"

    ecr = Aws::ECR::Client.new(region: region)

    # List all image repositories
    #
    res    = ecr.describe_all_repositories
    images = res.repositories.flat_map do |repo|
      ecr.describe_images(repository_name: repo.repository_name)
        .image_details
    end

    images.each do |image|
      image.region = region
      image.in_use = !image.image_uris.empty?
      image.elegible_for_cleanup = (image.stale?(options[:e]) && !image.in_use)
    end

    # We always show a list of images
    #
    print_image_list_header
    images.each { |image| print_image_list_entry(image) }

    if options[:c]
      images_to_delete =
        images.select(&:elegible_for_cleanup).group_by(&:repository_name)

      images_to_delete.each do |repository_name, pack|
        ecr.batch_delete_image(
          repository_name: repository_name,
          image_ids: pack.map { |i| { image_digest: i.image_digest } }
        )
      end
    end
  end
end