I want have some git branch deployments. For a particular branch, I want to keep the latest (sorted by imagePushedAt) and delete the remaining. This is what I am trying:
image_tags_json=$(aws ecr describe-images --repository-name bi-dagster --query 'sort_by(imageDetails,& imagePushedAt)[*].[imageTags[], imagePushedAt]' --output json)
# Check if there are any image tags returned
if [[ $(echo "$image_tags_json" | jq -r 'length') -eq 0 ]]; then
echo "No image tags found."
exit 1
fi
# Extract image tags containing the branch name along with timestamps
branch_image_tags=$(echo "$image_tags_json" | jq -r --arg branch "$branch_name" '.[] | select(.[0] | arrays) | select(.[0][] | contains($branch)) | "\(.[0]) \(.[1])"')
# Find the latest timestamp
latest_timestamp=$(echo "$branch_image_tags" | awk '{print $2}' | sort -r | head -n1)
# Output the image tags except the one with the latest timestamp
tags_to_delete=$(echo "$branch_image_tags" | awk -v latest="$latest_timestamp" '$2 != latest {print $1}')
#echo $tags_to_delete
image_digests=$(echo "$tags_to_delete" | jq -r '. | join(" ")')
echo $image_digests
for digest in $image_digests; do
aws ecr batch-delete-image --repository-name bi-dagster --image-ids imageDigest="$digest"
done
When I echo the image_digests, I get an output in this format. These are the correctly identified imageTags to be deleted, separated by space.
1233-1-DATA 238-1-DATA 157-1-DATA 661-1-DATA
But the problem comes when I try to actually delete them. I get this error on the last command.
{
"imageIds": [],
"failures": [
{
"imageId": {
"imageDigest": "661-1-DATA"
},
"failureCode": "InvalidImageDigest",
"failureReason": "Invalid request parameters: image digest should satisfy the regex '[a-zA-Z0-9-_+.]+:[a-fA-F0-9]+'"
}
]
}
Edit:
I create and push these images via Github. For each image, there's an "ImageIndex" and "Image". The "Image" always has a -- instead of the actual name (like in ImageIndex). My code now works to delete the ImageIndex objects but the Image objects are still there.

What you listed as the image digests output (
1233-1-DATA 238-1-DATA 157-1-DATA 661-1-DATA) are image tags not image digests. Change your code to something like the following: