Last active
July 9, 2021 13:00
-
-
Save yspreen/fe6bfd7eabeffe82a84f71616ab0cffe to your computer and use it in GitHub Desktop.
GCR Cleaner for GitHub Actions
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 | |
# To run in github actions, put this script in your repo, set your secrets, and add to your yaml: | |
# | |
# - name: Build and push image | |
# run: | | |
# echo '${{ secrets.JSON_KEY }}' | docker login -u _json_key --password-stdin https://"${{ secrets.HOSTNAME }}"; | |
# docker build . -t "${{ secrets.IMAGE }}"; | |
# docker push "${{ secrets.IMAGE }}"; | |
# - name: Clean GCR | |
# run: | | |
# echo '${{ secrets.JSON_KEY }}' > svc_account.json; | |
# docker run -v `pwd`/svc_account.json:/svc_account.json -v `pwd`/clean-gcr.sh:/clean-gcr.sh google/cloud-sdk:alpine /clean-gcr.sh "${{ secrets.IMAGE }}" | |
RED='\033[0;31m' | |
YELL='\033[1;33m' | |
NC='\033[0m' # No Color | |
IMAGES_TO_KEEP="3" | |
IMAGE_SECRET="$1" | |
IMAGE_REPO="$(echo "$IMAGE_SECRET" | sed 's|\(.*\)/.*|\1|')" | |
gcloud config set auth/credential_file_override /svc_account.json | |
# Get all images at the given image repo | |
echo -e "${YELL}Getting all images${NC}" | |
IMAGELIST=$(gcloud container images list --repository=${IMAGE_REPO} --format='get(name)') | |
echo "$IMAGELIST" | |
while IFS= read -r IMAGENAME; do | |
IMAGENAME=$(echo $IMAGENAME|tr -d '\r') | |
echo -e "${YELL}Checking ${IMAGENAME} for cleanup requirements${NC}" | |
# Get all the digests for the tag ordered by timestamp (oldest first) | |
DIGESTLIST=$(gcloud container images list-tags ${IMAGENAME} --sort-by timestamp --format='get(digest)') | |
DIGESTLISTCOUNT=$(echo "${DIGESTLIST}" | wc -l) | |
if [ ${IMAGES_TO_KEEP} -ge "${DIGESTLISTCOUNT}" ]; then | |
echo -e "${YELL}Found ${DIGESTLISTCOUNT} digests, nothing to delete${NC}" | |
continue | |
fi | |
# Filter the ordered list to remove the most recent 3 | |
DIGESTLISTTOREMOVE=$(echo "${DIGESTLIST}" | head -n -${IMAGES_TO_KEEP}) | |
DIGESTLISTTOREMOVECOUNT=$(echo "${DIGESTLISTTOREMOVE}" | wc -l) | |
echo -e "${YELL}Found ${DIGESTLISTCOUNT} digests, ${DIGESTLISTTOREMOVECOUNT} to delete${NC}" | |
# Do deletion or say nothing to do | |
if [ "${DIGESTLISTTOREMOVECOUNT}" -gt "0" ]; then | |
echo -e "${YELL}Removing ${DIGESTLISTTOREMOVECOUNT} digests${NC}" | |
while IFS= read -r LINE; do | |
LINE=$(echo $LINE|tr -d '\r') | |
gcloud container images delete ${IMAGENAME}@${LINE} --force-delete-tags --quiet | |
done <<< "${DIGESTLISTTOREMOVE}" | |
else | |
echo -e "${YELL}No digests to remove${NC}" | |
fi | |
done <<< "${IMAGELIST}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment