Cleanup Old Artifacts #85
This file contains 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: Cleanup Old Artifacts | |
on: | |
schedule: | |
- cron: '0 0 * * *' # Runs at midnight every day | |
workflow_dispatch: | |
jobs: | |
cleanup: | |
runs-on: ubuntu-latest | |
steps: | |
- name: Checkout code | |
uses: actions/checkout@v3 | |
- name: Delete old artifacts | |
env: | |
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} | |
run: | | |
#!/bin/bash | |
set -e | |
echo "Fetching workflow runs..." | |
# Fetch all workflow runs | |
runs=$(gh api repos/${{ github.repository }}/actions/runs --paginate --jq '.workflow_runs[] | {id: .id, name: .name, created_at: .created_at}') | |
# Group runs by workflow name and sort by creation date | |
grouped_runs=$(echo "$runs" | jq -s 'group_by(.name) | map({name: .[0].name, runs: sort_by(.created_at) | reverse})') | |
# Iterate over each workflow group | |
echo "$grouped_runs" | jq -c '.[]' | while read -r group; do | |
workflow_name=$(echo "$group" | jq -r '.name') | |
echo "Processing workflow: $workflow_name" | |
# Get all runs except the most recent one | |
old_runs=$(echo "$group" | jq -r '.runs[1:] | .[].id') | |
for run_id in $old_runs; do | |
echo "Fetching artifacts for run $run_id..." | |
artifacts=$(gh api repos/${{ github.repository }}/actions/runs/$run_id/artifacts --jq '.artifacts[].id') | |
for artifact_id in $artifacts; do | |
echo "Deleting artifact $artifact_id from run $run_id..." | |
gh api -X DELETE repos/${{ github.repository }}/actions/artifacts/$artifact_id | |
done | |
done | |
done |