Skip to content

Instantly share code, notes, and snippets.

@selfagency
Last active January 26, 2022 15:57
Show Gist options
  • Save selfagency/8cdf6c862bc4e4da52f83f10ad9b3ef9 to your computer and use it in GitHub Desktop.
Save selfagency/8cdf6c862bc4e4da52f83f10ad9b3ef9 to your computer and use it in GitHub Desktop.
[google app engine version cleanup script]
#!/usr/bin/env bash
###########################################################
# Use this script to delete old versions of GAE services. #
# Requires gcloud SDK to be installed and authorized. #
# Usage: #
# GCP_PROJECT=my_project GAE_SERVICE=my_service KEEP=5 \ #
# ./gae_version_cleanup.sh #
###########################################################
# check project is specified
if [ "$GCP_PROJECT" = "" ]; then
echo '`$GCP_PROJECT` variable required'
exit 1
fi
# check service is specified
if [ "$GAE_SERVICE" = "" ]; then
echo '`$GAE_SERVICE` variable required'
exit 1
fi
# check number of versions to keep is specified
if [ "$KEEP" = "" ] || [ "$KEEP" = 0 ]; then
echo '`$KEEP` variable required'
exit 1
fi
# fetch versions
VERSIONS=$(gcloud app versions list -q --project="$GCP_PROJECT" --service="$GAE_SERVICE" | cut -d ' ' -f3)
# printf "Current versions:\n%s\n\n" "$VERSIONS"
# count total number of versions
TOTAL=$(echo "$VERSIONS" | wc -l)
printf "Total versions of $GAE_SERVICE: %d.\n" "$TOTAL"
# get number of versions to delete
COUNT=$((TOTAL - KEEP))
printf "Keeping %d versions of $GAE_SERVICE.\n" "$KEEP"
printf "Deleting %d versions of $GAE_SERVICE.\n\n" "$COUNT"
COUNT=$((TOTAL - KEEP + 1))
# get the list of versions to delete
TO_DELETE=$(echo "$VERSIONS" | head -n $COUNT)
printf "Versions to delete:%s\n\n" "$TO_DELETE"
TO_DELETE=$(echo "$TO_DELETE" | tr '\n' ' ')
printf 'Executing: `gcloud app versions delete --project="%s" --service="%s" %s`\n\n' "$GCP_PROJECT" "$GAE_SERVICE" "$TO_DELETE"
# delete versions
{
gcloud app versions delete -q --project="$GCP_PROJECT" --service="$GAE_SERVICE" $TO_DELETE
} || {
echo "Failed to delete $GAE_SERVICE versions from $GCP_PROJECT"
exit 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment