Skip to content

Instantly share code, notes, and snippets.

@leogdion
Created June 14, 2026 22:37
Show Gist options
  • Select an option

  • Save leogdion/e1e26b33cd1958f6cbffa7e6288519be to your computer and use it in GitHub Desktop.

Select an option

Save leogdion/e1e26b33cd1958f6cbffa7e6288519be to your computer and use it in GitHub Desktop.
GitHub Actions: auto-delete a PR's stranded caches when the PR closes
# .github/workflows/cleanup-pr-caches.yml
#
# Deletes all GitHub Actions caches scoped to a PR's merge ref as soon as the
# PR closes (merged or not). Those caches live on refs/pull/<N>/merge and can
# NEVER be restored by any other branch, so after the PR closes they are pure
# dead weight that otherwise lingers until 7-day-inactivity or LRU eviction.
#
# Drop this file into each repo at: .github/workflows/cleanup-pr-caches.yml
name: Cleanup PR caches
on:
pull_request:
types: [closed]
permissions:
actions: write # required to delete caches
contents: read
jobs:
cleanup:
runs-on: ubuntu-latest
steps:
- name: Delete caches for this PR
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
REPO: ${{ github.repository }}
BRANCH: refs/pull/${{ github.event.pull_request.number }}/merge
run: |
echo "Clearing caches on $BRANCH for $REPO"
ids=$(gh api --paginate \
"/repos/$REPO/actions/caches?per_page=100&ref=$BRANCH" \
--jq '.actions_caches[].id')
if [ -z "$ids" ]; then
echo "No caches to delete."
exit 0
fi
for id in $ids; do
echo "Deleting cache $id"
gh api -X DELETE "/repos/$REPO/actions/caches/$id" || true
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment