Created
October 12, 2018 17:46
-
-
Save mmrobins/d36c75dc6fe1729f3a6d4bdb2b637a53 to your computer and use it in GitHub Desktop.
delete old ecr images
This file contains 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 = 'passport' | |
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