Skip to content

Instantly share code, notes, and snippets.

@ShubhamRasal
Last active March 3, 2023 06:39
Show Gist options
  • Save ShubhamRasal/e40efc33841c55651c3a6e634a300b17 to your computer and use it in GitHub Desktop.
Save ShubhamRasal/e40efc33841c55651c3a6e634a300b17 to your computer and use it in GitHub Desktop.
Github API to rerun failed jobs

List repository workflows [Workflow ID]

https://docs.github.com/en/rest/actions/workflows?apiVersion=2022-11-28#list-repository-workflows

List workflow runs for a workflow [RUN ID]

https://docs.github.com/en/rest/actions/workflow-runs?apiVersion=2022-11-28#list-workflow-runs-for-a-workflow

Rerun failed jobs for a run

https://docs.github.com/en/rest/actions/workflow-runs?apiVersion=2022-11-28#re-run-failed-jobs-from-a-workflow-run

Note:

  • To run the failed job using API, we need add following permissions to token
    • Read access to metadata
    • Read and Write access to actions
  • We need to get approval of admin for request.
#!/bin/bash
OWNER="shubhamrasal"
REPO="subfinder"
WORKFLOW_NAME="Build Test"
BEFORE_TIME="30 mins ago"
DATE=`date +%Y-%m-%d'T'%H:%M'Z' -d "$BEFORE_TIME"`
BRANCH="master"
TZ=UTC
workflowID=''
failedWorkflowRuns=''
function get_workflows() {
echo "Fetching workflows for $OWNER/$REPO/$WORKFLOW_NAME"
workflows=$(curl -L -sS \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GITHUB_TOKEN"\
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/repos/"$OWNER"/"$REPO"/actions/workflows)
workflowID=$(echo $workflows | jq -c '.workflows | .[] | select( .name | contains($workflow)) | .id' --arg workflow "$WORKFLOW_NAME")
}
function get_failed_workflow_runs(){
echo "Checking failed workflow runs for $workflowID"
failed_runs=$(curl -L -sS\
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GITHUB_TOKEN"\
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/repos/"$OWNER"/"$REPO"/actions/workflows/"$workflowID"/runs?branch="$BRANCH"\&status=failure)
failedWorkflowRuns=$(echo $failed_runs | jq -c '.workflow_runs | .[] | select ( .updated_at > $date ) | .id ' --arg date "$DATE" )
}
main() {
get_workflows
get_failed_workflow_runs
eval "arr=($failedWorkflowRuns)"
if [[ -z $arr ]]
then
echo "Could not find any failed workflows"
exit 0
fi
for s in "${arr[@]}"; do
echo "Rerunning failed workflow $s"
curl -L \
-X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GITHUB_TOKEN"\
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/repos/"$OWNER"/"$REPO"/actions/runs/$s/rerun-failed-jobs
done
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment