Repository navigation
Cleanup Old Workflow Runs #33
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
| # Copyright the Hyperledger Fabric contributors. All rights reserved. | |
| # | |
| # SPDX-License-Identifier: Apache-2.0 | |
| name: Cleanup Old Workflow Runs | |
| on: | |
| schedule: | |
| - cron: '0 2 * * *' | |
| workflow_dispatch: | |
| inputs: | |
| keep_runs: | |
| description: Number of latest completed runs to keep per workflow | |
| required: false | |
| default: '10' | |
| jobs: | |
| cleanup: | |
| runs-on: ubuntu-latest | |
| timeout-minutes: 30 | |
| concurrency: | |
| group: workflow-cleanup | |
| cancel-in-progress: false | |
| permissions: | |
| actions: write | |
| steps: | |
| - name: Delete old workflow runs | |
| uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 | |
| with: | |
| script: | | |
| const owner = context.repo.owner; | |
| const repo = context.repo.repo; | |
| const defaultKeep = 10; | |
| const inputKeep = Number(context.payload.inputs?.keep_runs || defaultKeep); | |
| const runsToKeep = Number.isFinite(inputKeep) && inputKeep > 0 ? inputKeep : defaultKeep; | |
| console.log(`Keeping latest ${runsToKeep} completed runs per workflow`); | |
| const workflows = await github.paginate(github.rest.actions.listRepoWorkflows, { | |
| owner, | |
| repo, | |
| per_page: 100, | |
| }); | |
| let deletedCount = 0; | |
| let failedCount = 0; | |
| for (const workflow of workflows) { | |
| const runs = await github.paginate(github.rest.actions.listWorkflowRuns, { | |
| owner, | |
| repo, | |
| workflow_id: workflow.id, | |
| status: 'completed', | |
| per_page: 100, | |
| }); | |
| runs.sort((a, b) => new Date(b.created_at) - new Date(a.created_at)); | |
| const staleRuns = runs.slice(runsToKeep); | |
| console.log(`${workflow.name}: found ${runs.length} completed runs, deleting ${staleRuns.length}`); | |
| for (const run of staleRuns) { | |
| try { | |
| await github.rest.actions.deleteWorkflowRun({ owner, repo, run_id: run.id }); | |
| deletedCount++; | |
| } catch (error) { | |
| failedCount++; | |
| console.log(`Failed to delete run ${run.id}: ${error.message}`); | |
| } | |
| } | |
| } | |
| console.log(`Deleted ${deletedCount} workflow runs, ${failedCount} failures`); |