Skip to content

Instantly share code, notes, and snippets.

@mboersma
Last active July 12, 2021 22:56
Show Gist options
  • Save mboersma/8e6053cf1437c346aed009dc0968c0d4 to your computer and use it in GitHub Desktop.
Save mboersma/8e6053cf1437c346aed009dc0968c0d4 to your computer and use it in GitHub Desktop.
Delete unused CAPZ storage accounts
#!/bin/bash
set -euo pipefail
RESOURCE_GROUP=${RESOURCE_GROUP:-cluster-api-images}
PUBLISHER=${PUBLISHER:-cncf-upstream}
OFFER=${OFFER:-capi}
which pub &> /dev/null || (echo "Please install pub from https://github.com/devigned/pub/releases" && exit 1)
# Get URLs in use by the marketplace offer
OFFER=$(pub offers show -p "$PUBLISHER" -o "$OFFER")
URLS=$(echo "${OFFER}" | jq '.definition["plans"][]."microsoft-azure-corevm.vmImagesPublicAzure"[].osVhdUrl')
NOW=$(date +%s)
IFS=$'\n'
# For each storage account in the subscription,
for account in $(az storage account list -g "${RESOURCE_GROUP}" -o tsv --query "[?starts_with(name, 'capi')].[name,creationTime]"); do
IFS=$'\t' read -r storage_account creation_time <<< "$account"
created=$(date -d "${creation_time}" +%s 2>/dev/null || date -j -f "%F" "${creation_time}" +%s 2>/dev/null)
age=$(( (NOW - created) / 86400 ))
# if it's older than a month
if [[ $age -gt 30 ]]; then
# and it has the right naming pattern but isn't referenced in the offer osVhdUrls
if [[ ${storage_account} =~ ^capi[0-9]{10} ]] && [[ ! ${URLS} =~ ${storage_account} ]]; then
# delete it.
echo "Deleting unreferenced storage account ${storage_account} that is ${age} days old"
echo az storage account delete -g "${RESOURCE_GROUP}" -n "${storage_account}" -y
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment