Class: Ecr::Cleaner

Inherits:
Object
  • Object
show all
Includes:
Ufo::AwsService, Ufo::Util
Defined in:
lib/ufo/ecr/cleaner.rb

Instance Method Summary collapse

Methods included from Ufo::AwsService

#cloudformation, #cloudwatchlogs, #ec2, #ecr, #ecs, #elb

Methods included from Ufo::Util

#default_cluster, #display_params, #execute, #pretty_time, #settings, #task_definition_arns, #user_params

Constructor Details

#initialize(docker_image_name, options = {}) ⇒ Cleaner

Returns a new instance of Cleaner.



11
12
13
14
15
16
17
18
# File 'lib/ufo/ecr/cleaner.rb', line 11

def initialize(docker_image_name, options={})
  # docker_image_name does not containg the tag
  # Example: 123456789.dkr.ecr.us-east-1.amazonaws.com/image
  @docker_image_name = docker_image_name
  @options = options
  @keep = options[:ecr_keep] || settings[:ecr_keep]
  @tag_prefix = options[:tag_prefix] || "ufo"
end

Instance Method Details

#cleanupObject



20
21
22
23
24
25
26
27
# File 'lib/ufo/ecr/cleaner.rb', line 20

def cleanup
  return false unless ecr_image?
  return false unless @keep
  update_auth_token
  image_tags = fetch_image_tags
  delete_tags = image_tags[@keep..-1] # ordered by most recent images first
  delete_images(delete_tags)
end

#delete_images(tags) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/ufo/ecr/cleaner.rb', line 37

def delete_images(tags)
  return if tags.nil? || tags.empty?
  unless @options[:mute]
    puts "Keeping #{@keep} most recent ECR images."
    puts "Deleting these ECR images:"
    tag_list = tags.map { |t| "  #{repo_name}:#{t}" }
    puts tag_list
  end
  image_ids = tags.map { |tag| {image_tag: tag} }
  ecr.batch_delete_image(
    repository_name: repo_name,
    image_ids: image_ids) unless @options[:noop]
end

#ecr_image?Boolean

Returns:

  • (Boolean)


62
63
64
# File 'lib/ufo/ecr/cleaner.rb', line 62

def ecr_image?
  @docker_image_name =~ /\.amazonaws\.com/
end

#fetch_image_tagsObject



29
30
31
32
33
34
35
# File 'lib/ufo/ecr/cleaner.rb', line 29

def fetch_image_tags
  ecr.list_images(repository_name: repo_name).
    image_ids.
    map { |image_id| image_id.image_tag }.
    select { |image_tag| image_tag =~ Regexp.new("^#{@tag_prefix}-") }.
    sort.reverse
end

#repo_nameObject



57
58
59
60
# File 'lib/ufo/ecr/cleaner.rb', line 57

def repo_name
  # @docker_image_name example: 123456789.dkr.ecr.us-east-1.amazonaws.com/image
  @docker_image_name.split('/').last
end

#update_auth_tokenObject



51
52
53
54
55
# File 'lib/ufo/ecr/cleaner.rb', line 51

def update_auth_token
  repo_domain = "#{@docker_image_name.split('/').first}"
  auth = Ecr::Auth.new(repo_domain)
  auth.update
end