Skip to content

Instantly share code, notes, and snippets.

@dmerrick
Last active August 23, 2020 14:04
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save dmerrick/503655db7ff90b70c2d15fc9dd83b45e to your computer and use it in GitHub Desktop.
Save dmerrick/503655db7ff90b70c2d15fc9dd83b45e to your computer and use it in GitHub Desktop.
Delete old ECR images
#!/usr/bin/env ruby
# this script will delete ECR images that are older than N days
require 'date'
require 'json'
# customize this script
repo = 'snapdocs'
delete_if_older_than = 60 # days
# get the list of all images
json_output = `aws ecr describe-images --repository-name #{repo} --output json`
images = JSON.parse(json_output)['imageDetails']
# find the images to delete
images_to_delete = []
images.each do |i|
date_pushed = DateTime.strptime(i['imagePushedAt'].to_s,'%s')
age_in_days = (DateTime.now - date_pushed).to_i
if age_in_days > delete_if_older_than
images_to_delete << i
end
end
# sanity check
puts "There are #{images_to_delete.size} images that will be deleted."
puts "Is that okay?"
input = STDIN.gets.strip
exit 5 unless input =~ /^y/i
# actually delete the images
# 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 snapdocs --image-ids #{image_ids}`
end
puts "Done!"
@erstaples
Copy link

Very helpful, thanks! You should replace snapdocs on line 35 with #{repo}.

@jclinto1
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment