Last active
March 29, 2019 16:32
-
-
Save embolalia/245d080c2aafc4a85e6564c53668aa5f to your computer and use it in GitHub Desktop.
Get rid of old ecr images
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# this script will delete ECR images that are older than N days | |
require 'date' | |
require 'json' | |
# customize this script | |
repo = 'changeme' | |
delete_if_older_than = 180 # days | |
# get the list of all images | |
json_output = `aws ecr describe-images --repository-name #{repo} --output json --region us-west-2` | |
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 | |
#puts "#{i['imageDigest']} #{age_in_days}" | |
images_to_delete << i | |
end | |
end | |
# sanity check | |
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 | |
# 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 #{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