-
-
Save siigna/9fd21b452231b2dff1caadc686816d29 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 = '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!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment