Skip to content

Instantly share code, notes, and snippets.

@JamesCullum
Created January 21, 2021 16:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JamesCullum/7321bdcc2dcec643217667936281aed7 to your computer and use it in GitHub Desktop.
Save JamesCullum/7321bdcc2dcec643217667936281aed7 to your computer and use it in GitHub Desktop.
Bash script to automatically rollback to the last successful pipeline, by re-running the deployment job of it. Should be run with sufficient time after the previous jobs to make sure the check can properly know if the startup failed or not.
#!/bin/bash
if curl --output /dev/null --silent --head --fail "http://127.0.0.1:80"; then
echo "Website appears to be available"
else
echo "Website not available, initiating rollback"
LASTSUCCESSPIPELINE=$(curl -k --silent --header "PRIVATE-TOKEN: $CI_JOB_TOKEN" "https://gitlab.example.com/api/v4/projects/1/pipelines?status=success&scope=finished" | jq '.[0].id')
if [ -z "$LASTSUCCESSPIPELINE" ]; then
echo "Cannot get last pipeline id"
exit 1
fi
echo "Rolling back to pipeline id $LASTSUCCESSPIPELINE"
# Change name of job name in the line below
RETRYJOBID=$(curl -k --silent --header "PRIVATE-TOKEN: $CI_JOB_TOKEN" "https://gitlab.example.com/api/v4/projects/1/pipelines/$LASTSUCCESSPIPELINE/jobs" | jq '.[] | select(.name == "deploy") | .id')
if [ -z "$LASTSUCCESSPIPELINE" ]; then
echo "Cannot get job of this pipeline to retry"
exit 1
fi
echo "Retrying job id $RETRYJOBID"
curl -k --silent --request POST --header "PRIVATE-TOKEN: $CI_JOB_TOKEN" "https://gitlab.example.com/api/v4/projects/1/jobs/$RETRYJOBID/retry" 2>/dev/null
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment