Skip to content

Instantly share code, notes, and snippets.

@lelandbatey
Created November 15, 2023 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lelandbatey/719b1c76c131daede8559ab37a098045 to your computer and use it in GitHub Desktop.
Save lelandbatey/719b1c76c131daede8559ab37a098045 to your computer and use it in GitHub Desktop.
Re-run your latest failing CircleCI workflow for a given Github project till it succeeds
#!/bin/bash
# A script to re-run your latest failing workflow for a given Github project
# Examples:
#
# circleci-retry-failing-workflow.bash orgservice
#
# circleci-retry-failing-workflow.bash lichee
if [ $# -eq 0 ]; then
echo "# No arguments supplied"
fi
VCS="gh"
REPO="$1"
ORG="getoutreach"
SLUG="${VCS}/${ORG}/${REPO}"
echoerr() { echo "$@" 1>&2; }
printferr() { printf "$@" 1>&2; }
dbgecho() {
if [ -n "${DEBUG}" ]; then
echoerr "$@";
fi
}
workflows_of_pipeline() {
PIPELINE_ID="$1"
curl -s --request GET \
--url "https://circleci.com/api/v2/pipeline/${PIPELINE_ID}/workflow" \
--header "Circle-Token: ${CIRCLE_TOKEN}"
}
latest_workflow() {
PIPELINE_ID="$1"
workflows_of_pipeline "${PIPELINE_ID}" | jq -r '.items[0]'
}
jobs_of_workflow() {
WORKFLOW_ID="$1"
curl -s --request GET \
--url "https://circleci.com/api/v2/workflow/${WORKFLOW_ID}/job" \
--header "Circle-Token: ${CIRCLE_TOKEN}"
}
LATEST_PIPELINE="$(curl -s --request GET \
--url "https://circleci.com/api/v2/project/${SLUG}/pipeline/mine" \
--header "Circle-Token: ${CIRCLE_TOKEN}" | jq '.items[0]')"
dbgecho "${LATEST_PIPELINE}"
LATEST_PIPELINE_ID="$(echo "${LATEST_PIPELINE}" | jq -r '.id')"
PIPELINE_URL="https://app.circleci.com/pipelines/${SLUG}/$(echo "${LATEST_PIPELINE}" | jq '.number')"
printferr "# First pipeline in %12s %50s branch: %20s\n" "${REPO}" "${PIPELINE_URL}" "$(echo "${LATEST_PIPELINE}" | jq -r '.vcs.branch')"
while true; do
LW="$(latest_workflow "${LATEST_PIPELINE_ID}")"
LW_STATUS="$(echo "${LW}" | jq -r '.status')"
LW_ID="$(echo "${LW}" | jq -r '.id')"
printferr '# %d %s %s Status: %s\n' "$(date "+%s")" "$(date "+%Y-%m-%d %H:%M:%S.%N%z" )" "${PIPELINE_URL}" "${LW_STATUS}"
if [ "${LW_STATUS}" == "success" ]; then
break
elif [ "${LW_STATUS}" == "failed" ]; then
echoerr "Re-run the thing"
CJOBS="$(jobs_of_workflow "${LW_ID}")"
#echo "${CJOBS}" | jq .
FAILED_IDS="$(echo "${CJOBS}" | jq '.items | .[] | select( .status == "failed" ) | .id' | jq -r -s -c '.')"
curl -s --request POST \
--url "https://circleci.com/api/v2/workflow/${LW_ID}/rerun" \
--header "Circle-Token: ${CIRCLE_TOKEN}" \
--header 'content-type: application/json' \
--data '{"enable_ssh":false,"from_failed":true,"sparse_tree":false}'
echo
#--data '{"enable_ssh":false,"from_failed":true,"jobs":'"${FAILED_IDS}"',"sparse_tree":false}'
fi
sleep 30
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment