Add cleanup action

This commit is contained in:
Anders da Silva Rytter Hansen 2026-05-07 22:32:55 -03:00
commit 77d4ee0f38

View file

@ -0,0 +1,43 @@
name: Clean up Forgejo Container Registry
on:
schedule:
- cron: '0 0 * * 0' # Runs every Sunday at midnight
workflow_dispatch: # Allows manual triggering
jobs:
delete-old-images:
runs-on: almalinux-10
steps:
- name: Delete old versions
run: |
REGISTRY="forge.pc-rytteren.dk"
OWNER="${{ github.repository_owner }}"
IMAGE="my-ostree-os"
MIN_KEEP=50
TOKEN="${{ secrets.PACKAGE_TOKEN }}"
# Fetch all container packages with this name, sorted oldest first (by id)
# API returns a list of package objects, each with "id" and "version"
RAW=$(curl -s -H "Authorization: token ${TOKEN}" \
"https://${REGISTRY}/api/v1/packages/${OWNER}?type=container&q=${IMAGE}&limit=200")
# Filter only packages with the correct name and extract id, sort oldest first
IDS=$(echo "$RAW" | tr '{' '\n' | grep "\"name\":\"${IMAGE}\"" | \
sed 's/.*"id":\([0-9]*\).*/\1/' | sort -n)
TOTAL=$(echo "$IDS" | grep -c '[0-9]' || true)
echo "Found ${TOTAL} packages total, keeping ${MIN_KEEP}"
if [ "$TOTAL" -le "$MIN_KEEP" ]; then
echo "No packages to delete"
exit 0
fi
# Delete the oldest (lowest ids) beyond MIN_KEEP
TO_DELETE=$(echo "$IDS" | head -n $(( TOTAL - MIN_KEEP )))
for ID in $TO_DELETE; do
echo "Deleting package id: ${ID}"
curl -s -X DELETE -H "Authorization: token ${TOKEN}" \
"https://${REGISTRY}/api/v1/packages/${OWNER}/${ID}"
done