Skip to content

Instantly share code, notes, and snippets.

@soderlind
Last active December 22, 2024 21:13
Delete failed and cancelled GitHub Actions workflow runs for a given workflow

Delete failed and cancelled GitHub Actions workflow runs

The script will remove failed and cancelled workflow runs from your GitHub Action workflow history log.

failed-workflow-run

Prerequisite

Installation

Usage

delete-failed-ga-runs.sh [-d] <repository> <workflow-name>

  • -d: Do a dry run, i.e. just show me what's going to happen, but don't delete anything.
  • <repository>: owner/repo-name
  • <workflow-name>: the workflow file name, e.g.: myworkflow.yml
#!/usr/bin/env bash
# Delete failed and cancelled workflow runs for a given workflow
# Usage: delete-failed-ga-runs.sh [-d] <repository> <workflow-name>
# -d: dry run mode
set -eo pipefail
# Parse arguments
DRY_RUN=0
while getopts "d" opt; do
case $opt in
d) DRY_RUN=1 ;;
*) exit 1 ;;
esac
done
shift $((OPTIND - 1))
REPOSITORY=$1
WORKFLOW_NAME=$2
MAX_PARALLEL=5
RATE_LIMIT_SLEEP=0.2
# Validate arguments
if [[ -z "$REPOSITORY" || -z "$WORKFLOW_NAME" ]]; then
echo "Usage: $0 [-d] <repository> <workflow-name>"
exit 1
fi
delete_run() {
local run_id=$1
if [[ $DRY_RUN -eq 1 ]]; then
echo "[DRY RUN] Would delete run $run_id"
return 0
fi
echo "Deleting run $run_id..."
if gh api --silent --method DELETE \
-H "Accept: application/vnd.github+json" \
-H "X-GitHub-Api-Version: 2022-11-28" \
"/repos/$REPOSITORY/actions/runs/$run_id"; then
echo "✓ Deleted run $run_id"
else
echo "✗ Failed to delete run $run_id"
return 1
fi
sleep $RATE_LIMIT_SLEEP
}
export -f delete_run
export REPOSITORY
export RATE_LIMIT_SLEEP
export DRY_RUN
echo "Fetching failed runs for workflow $WORKFLOW_NAME in $REPOSITORY..."
RUNS=$(gh api \
-H "Accept: application/vnd.github+json" \
-H "X-GitHub-Api-Version: 2022-11-28" \
"/repos/$REPOSITORY/actions/workflows/$WORKFLOW_NAME/runs" \
--paginate \
--jq '.workflow_runs[] | select(.conclusion == "failure" or .conclusion == "startup_failure" or .conclusion == "cancelled") | .id')
RUN_COUNT=$(echo "$RUNS" | grep -c '^' || true)
echo "Found $RUN_COUNT failed runs"
if [[ $RUN_COUNT -eq 0 ]]; then
exit 0
fi
echo "$RUNS" | xargs -P $MAX_PARALLEL -I {} bash -c 'delete_run "$@"' _ {}
echo "Completed deletion process"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment