Skip to content

Instantly share code, notes, and snippets.

@mmrobins
Created August 27, 2018 23:56
Show Gist options
  • Save mmrobins/f0a7662e59bd485d45a1ee8ff2f35fe1 to your computer and use it in GitHub Desktop.
Save mmrobins/f0a7662e59bd485d45a1ee8ff2f35fe1 to your computer and use it in GitHub Desktop.
ecr-cleanup
#!/usr/bin/env ruby
# this script will delete ECR images that are older than N days
require 'date'
require 'json'
# customize this script
repo = ARGV[0]
delete_if_older_than = ARGV[1].to_i # days
json_output = `aws ecr describe-images --repository-name #{repo} --output json --region us-west-2`
images = JSON.parse(json_output)['imageDetails']
images_to_delete = images.sort_by { |i| i['imagePushedAt'] }.select do |i|
date_pushed = DateTime.strptime(i['imagePushedAt'].to_s, '%s')
age_in_days = (DateTime.now - date_pushed).to_i
image_size = i['imageSizeInBytes'] / 1_000_000
puts "#{i['imageDigest']} #{image_size}MB #{age_in_days} days old"
age_in_days > delete_if_older_than
end
puts "There are #{images.size} total"
puts "There are #{images_to_delete.size} images that will be deleted."
require 'pp'
# pp images_to_delete
puts 'Is that okay?'
input = STDIN.gets.strip
exit 5 unless input =~ /^y/i
# AWS has a limit of 100 images in a batch
images_to_delete.each_slice(100) do |batch|
image_ids = batch.map { |i| "imageDigest=#{ i['imageDigest'] }" }.join(' ')
puts `aws ecr batch-delete-image --repository-name #{repo} --image-ids #{image_ids} --region us-west-2`
end
puts 'Done!'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment