How to Schedule Cleanup of Old Artifacts in GitHub Actions
A nightly job can list artifacts via the REST API and delete the ones older than a cutoff to free storage.
Retention days remove artifacts eventually, but a scheduled cleanup that calls the artifacts REST API with gh reclaims space faster on a fixed cadence.
Steps
- Schedule the cleanup nightly.
- List artifacts with
gh apiand filter by age. - Delete each expired artifact by id.
Workflow
.github/workflows/ci.yml
on:
schedule:
- cron: '0 3 * * *'
permissions:
actions: write
jobs:
purge:
runs-on: ubuntu-latest
steps:
- run: |
cutoff=$(date -d '7 days ago' +%s)
gh api "repos/$GITHUB_REPOSITORY/actions/artifacts?per_page=100" \
--jq '.artifacts[] | [.id, .created_at] | @tsv' |
while IFS=$'\t' read -r id created; do
[ "$(date -d "$created" +%s)" -lt "$cutoff" ] &&
gh api -X DELETE "repos/$GITHUB_REPOSITORY/actions/artifacts/$id"
done
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}Gotchas
- The API paginates at 100 items; loop over pages for large repos.
- Setting a shorter
retention-dayson upload avoids most manual cleanup.
Related guides
How to Run a Nightly Cleanup of Stale Branches in GitHub ActionsDelete merged or long-idle branches on a nightly GitHub Actions schedule using the gh CLI, keeping the branch…
How to Run a Workflow on a Cron Schedule in GitHub ActionsTrigger a GitHub Actions workflow on a recurring timetable with on.schedule and a five-field POSIX cron expre…