Created
December 12, 2024 21:40
-
-
Save mikeatlas/d617319b6f0ccd8c10d676e8d9508a27 to your computer and use it in GitHub Desktop.
Script to batch delete old ECR images. Mostly written by ChatGPT
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
#!/bin/bash | |
# Repository name | |
REPO_NAME="my-repo-name" | |
# Get the date 2 years ago in UTC format | |
TWO_YEARS_AGO=$(date -v-2y -u +"%Y-%m-%dT%H:%M:%SZ") | |
# Retrieve and filter images older than 2 years | |
IMAGES_TO_DELETE=$(aws ecr describe-images \ | |
--repository-name $REPO_NAME \ | |
--query "imageDetails[?imagePushedAt<'$TWO_YEARS_AGO'].{digest:imageDigest, tags:imageTags}" \ | |
--output json) | |
# Parse the JSON and process images | |
echo "$IMAGES_TO_DELETE" | jq -c '.[]' | while read -r IMAGE; do | |
DIGEST=$(echo "$IMAGE" | jq -r '.digest') | |
TAGS=$(echo "$IMAGE" | jq -r '.tags[]?' 2>/dev/null) | |
# Try deleting the image | |
echo "Attempting to delete image with digest: $DIGEST" | |
DELETE_RESPONSE=$(aws ecr batch-delete-image \ | |
--repository-name $REPO_NAME \ | |
--image-ids imageDigest=$DIGEST 2>&1) | |
# Debug: Output DELETE_RESPONSE for verification | |
echo "Delete response: $DELETE_RESPONSE" | |
if echo "$DELETE_RESPONSE" | grep -q "ImageReferencedByManifestList"; then | |
echo "Image $DIGEST is referenced by a manifest list. Resolving..." | |
# Extract manifest list digest directly from the error message | |
MANIFEST_DIGEST=$(echo "$DELETE_RESPONSE" | grep -o 'sha256:[a-f0-9]\{64\}' | tail -n1) | |
# Debug: Output the extracted manifest digest | |
echo "Extracted manifest digest: $MANIFEST_DIGEST" | |
if [ -n "$MANIFEST_DIGEST" ]; then | |
echo "Deleting manifest list with digest: $MANIFEST_DIGEST" | |
aws ecr batch-delete-image --repository-name $REPO_NAME --image-ids imageDigest=$MANIFEST_DIGEST | |
else | |
echo "Failed to extract manifest list digest for image: $DIGEST" | |
fi | |
# Retry deleting the image | |
echo "Retrying deletion of image: $DIGEST" | |
aws ecr batch-delete-image --repository-name $REPO_NAME --image-ids imageDigest=$DIGEST | |
else | |
echo "Deleted image with digest: $DIGEST" | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment