Search code examples
cachinggithub-actions

How to clear GitHub caches in workflow using gh?


I want to periodically remove all GitHub caches for my project using a workflow action. While this has been discussed before, the GitHub toolkit has evolved and the proposed solutions seem rather messy and hard to understand.

The project is private and its organization on the free plan, if that's of relevance.

I figured it should be possible to run gh cache delete --all in the workflow. So I devised the following workflow:

name: Clear all GitHub actions caches
on:
  schedule:
    - cron: "0 4 * * 0"
  workflow_dispatch:

jobs:
  clear-github-caches:
    name: Clear all GitHub action caches
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - run: |
          gh repo list
          gh cache delete --all --repo me/my-project
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

However, when I run it, it fails with:

me/my-project   <description>   private 2023-11-05T17:17:15Z
HTTP 403: Resource not accessible by integration (https://api.github.com/repos/me/my-project/actions/caches?per_page=100)

I also tried to use a local work copy by adding:

      - uses: actions/checkout@v3

but this did not change anything.

Do I need a different permission than "contents: write"? Or am I missing something else?


Solution

  • The gh cache delete docs mentions:

    Deletion requires authorization with the "repo" scope.

    which means you need to create a PAT (Personal Access Token) for this with repo scope as the default GITHUB_TOKEN doesn't have it.

    And, you do need the checkout step also (or you'll have to specify the repo using --repo flag with gh commands).