Delete Old Workflow Runs #2
This file contains hidden or 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: "Delete Old Workflow Runs" | |
| on: | |
| schedule: | |
| # Run every week on Sunday at 00:00 UTC | |
| - cron: '0 0 * * 0' | |
| workflow_dispatch: | |
| permissions: | |
| actions: write | |
| contents: read | |
| jobs: | |
| delete-old-runs: | |
| runs-on: ubuntu-latest | |
| timeout-minutes: 10 | |
| steps: | |
| - name: Delete workflow runs older than 30 days | |
| uses: actions/github-script@v7 | |
| with: | |
| script: | | |
| const days_to_keep = 30; | |
| const minimum_runs_to_keep = 6; | |
| const cutoff_date = new Date(Date.now() - (days_to_keep * 24 * 60 * 60 * 1000)); | |
| const workflows = await github.rest.actions.listRepoWorkflows({ | |
| owner: context.repo.owner, | |
| repo: context.repo.repo | |
| }); | |
| for (const workflow of workflows.data.workflows) { | |
| console.log(`Processing workflow: ${workflow.name} (${workflow.id})`); | |
| const runs = await github.rest.actions.listWorkflowRuns({ | |
| owner: context.repo.owner, | |
| repo: context.repo.repo, | |
| workflow_id: workflow.id, | |
| per_page: 100 | |
| }); | |
| // Sort runs by created date, newest first | |
| const sortedRuns = runs.data.workflow_runs.sort((a, b) => | |
| new Date(b.created_at) - new Date(a.created_at) | |
| ); | |
| // Keep the most recent runs and delete older ones | |
| for (let i = 0; i < sortedRuns.length; i++) { | |
| const run = sortedRuns[i]; | |
| const run_date = new Date(run.created_at); | |
| // Keep minimum number of recent runs | |
| if (i < minimum_runs_to_keep) { | |
| console.log(`Keeping recent run #${run.id} (${run.name})`); | |
| continue; | |
| } | |
| // Delete runs older than cutoff date | |
| if (run_date < cutoff_date) { | |
| console.log(`Deleting old run #${run.id} from ${run.created_at}`); | |
| try { | |
| await github.rest.actions.deleteWorkflowRun({ | |
| owner: context.repo.owner, | |
| repo: context.repo.repo, | |
| run_id: run.id | |
| }); | |
| } catch (error) { | |
| console.log(`Failed to delete run #${run.id}: ${error.message}`); | |
| } | |
| } | |
| } | |
| } | |
| console.log('Cleanup complete!'); | |