Aniket
Aniket

Reputation: 545

Want to filter gcp docker image digest from container registry

I made a script which is filter the gcp docker container digest who is 25 days old, and the result will loop into gcloud docker container delete command. It's working, but my concern is if the latest one itself on 25 days older then my script will delete them also. I want to skip if there is only the latest one, it will skip to delete.

#!/bin/bash 
DIGESTS=$(gcloud container images list-tags ** --format 'value(digest)' --filter="timestamp.datetime < '$(date +"%Y-%m-%d" --date="25 days ago")'")
COUNT=0 
echo "Keeping the latest 2 digest of the service" 
for DIGEST in $DIGESTS 
do 
((COUNT++)) 
if [[ $COUNT -gt 2 ]] ; 
then echo "Going to delete version $DIGEST of the zeus service." 
gcloud container images delete -q ***@sha256:$DIGEST 
else echo "Going to keep version $DIGEST of the name service." 
fi 
done

Upvotes: 0

Views: 921

Answers (1)

Romeo Ninov
Romeo Ninov

Reputation: 7225

You can add check of the number of containers and exit if it's only one

#!/bin/bash 
DIGESTS=$(gcloud container images list-tags ** --format 'value(digest)' --filter="timestamp.datetime < '$(date +"%Y-%m-%d" --date="25 days ago")'")
WCOUNT=$(echo $DIGESTS|wc -w)
if [ "$WCOUNT" -eq 1 ]
 then exit
fi
echo "Keeping the latest 2 digest of the service" 
for DIGEST in $DIGESTS 
do 
if [[ $WCOUNT -gt 2 ]] ; 
then echo "Going to delete version $DIGEST of the zeus service." 
gcloud container images delete -q ***@sha256:$DIGEST 
else echo "Going to keep version $DIGEST of the name service." 
fi 
((WCOUNT--)) 
done

Upvotes: 2

Related Questions