Skip to content
Latchkey

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 api and 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-days on upload avoids most manual cleanup.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →