Delete Old GHCR Stage #19
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
name: Delete Old GHCR Stage | |
on: | |
schedule: | |
- cron: "0 0 * * 0" # Runs every Sunday at midnight (UTC) | |
workflow_dispatch: # Allows manual trigger | |
permissions: | |
packages: write | |
contents: read | |
jobs: | |
delete-ghcr-image: | |
runs-on: ubuntu-latest | |
if: github.ref == 'refs/heads/develop' | |
steps: | |
- name: Install GitHub CLI | |
run: | | |
sudo apt update | |
sudo apt install gh -y | |
- name: Check Authentication Status | |
env: | |
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} | |
run: gh auth status | |
- name: Get Image Versions | |
env: | |
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} | |
IMAGE_NAME: "odc-stats-stages" | |
run: | | |
gh api --paginate /user/packages/container/$IMAGE_NAME/versions > versions.json || echo "[]" > versions.json | |
cat versions.json | jq '.[] | {id, created_at}' | |
- name: Delete Old Image Versions | |
env: | |
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} | |
IMAGE_NAME: "odc-stats-stages" | |
DAYS_THRESHOLD: 7 | |
run: | | |
NOW=$(date -u +%s) | |
THRESHOLD=$((NOW - DAYS_THRESHOLD * 86400)) | |
for row in $(cat versions.json | jq -c '.[]'); do | |
ID=$(echo $row | jq -r '.id') | |
CREATED_AT=$(echo $row | jq -r '.created_at') | |
CREATED_TIME=$(date -d "$CREATED_AT" +%s) | |
if [[ $CREATED_TIME -lt $THRESHOLD ]]; then | |
echo "Deleting image version $ID (created at $CREATED_AT)" | |
gh api --method DELETE /user/packages/container/$IMAGE_NAME | |
fi | |
done |