Skip to content

Instantly share code, notes, and snippets.

@BlackChar
Created July 21, 2017 16:48
Show Gist options
  • Save BlackChar/ce6f9c487596b4be421b88ee91aef85f to your computer and use it in GitHub Desktop.
Save BlackChar/ce6f9c487596b4be421b88ee91aef85f to your computer and use it in GitHub Desktop.
Script searches for images pushed to ECR older than specified (default is 30 days)
#!/bin/bash
# Usage: $0 {days} [--delete]
# Script searches for images pushed to ECR older than specified (default is 30 days)
# Checks if image is not running in any ECS container and then prints deletion command
# or deletes it directly.
#
# Script needs working AWSCLI config (`aws configure`) to function
DAYS=${1:-"30"}
THRESHOLD=$(date -d "$DAYS days ago" +%s)
RUNNING=`mktemp` || exit 1
echo --------------
echo Searching for running containers
aws ecs list-clusters | while read clsTag clsArn; do
echo Found cluster $clsArn
aws ecs list-tasks --cluster "$clsArn" --desired-status RUNNING --output text | while read tskTag tskArns; do
echo Found taskArn $tskArns
aws ecs describe-tasks --cluster "$clsArn" --tasks "$tskArns" --output text | while read -a tskInfo; do
if [[ ${tskInfo[0]} == "TASKS" ]]; then
tskDefArn=${tskInfo[9]};
echo "Found TaskDefinitionArn $tskDefArn"
aws ecs describe-task-definition --task-definition "$tskDefArn" | while read -a tskDefInfo; do
if [[ ${tskDefInfo[0]} == "CONTAINERDEFINITIONS" ]]; then
imgTag=${tskDefInfo[3]}
echo -n "Found tagged image $imgTag"
IFS='/:' read repoUri repoName imgTag <<< "$imgTag"
echo " Repository:$repoName Tag:$imgTag"
aws ecr describe-images --repository-name $repoName --image-ids "imageTag=$imgTag" | while read imgTag imgDigest _; do
if [[ $imgTag == "IMAGEDETAILS" ]]; then
echo Image digest: $imgDigest;
echo $imgDigest >> $RUNNING;
fi
done
fi
done
fi
done
done
done
echo --------------
echo Searching images older than `date -d "$DAYS days ago"` \($THRESHOLD\)
aws ecr describe-repositories --output text | while read repoTag repoCreated registryId repoArn repoName repoUri ; do
echo Found repository $repoName
aws ecr describe-images --repository-name $repoName --output text | while read imgTag imgDigest imgCreated imgSize ; do
if [[ $imgTag = 'IMAGEDETAILS' && ($imgCreated < $THRESHOLD) ]]; then
echo -n Found image $imgDigest
if grep -q $imgDigest $RUNNING; then
echo "...image is running. Skipped."
else
if [[ $2 == "--delete" ]]; then
echo "...deleting!"
aws ecr batch-delete-image --repository-name $repoName --image-ids "imageDigest=$imgDigest"
else
echo "...should be deleted."
echo aws ecr batch-delete-image --repository-name $repoName --image-ids "imageDigest=$imgDigest"
fi
fi
fi
done
done
rm -f $RUNNING
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment