Skip to content

Instantly share code, notes, and snippets.

@antonioaguilar
Forked from claytonrcarter/README.md
Created August 3, 2023 21:17
Show Gist options
  • Save antonioaguilar/27036e4c4f417288c2689dc8b50b49f4 to your computer and use it in GitHub Desktop.
Save antonioaguilar/27036e4c4f417288c2689dc8b50b49f4 to your computer and use it in GitHub Desktop.
Bash script to check GitLab pipeline status

A super simple bash script to check the status of a GitLab CI pipeline.

$ git push
...
$ git pipeline-status
Status of last pipeline for user/project on gitlab/master:
"pending"
...
$ git pipeline-status
Status of last pipeline for user/project on gitlab/master:
"running"
...
$ git pipeline-status
Status of last pipeline for user/project on gitlab/master:
"success"

Prerequisites

Aside from git and curl, you will need jq (see https://stedolan.github.io/jq/, or just brew install jq).

Your GitLab private access token needs to be set in an environment variable called GITLAB_API_PRIVATE_TOKEN.

Your GitLab remote needs to be named either gitlab or origin. If it's not, you can override those via the GITLAB_REMOTE environment variable.

~/bin needs to be in your $PATH

Install

  1. Copy the attached git-pipeline-status into your ~/bin directory
  2. Make it executable: chmod +x ~/bin/git-pipeline-status

Usage

git pipeline-status

How?!

"How does putting a random script in my ~/bin make this work?" See git source and this coderwall blog post

#!/bin/bash
if ! git status > /dev/null 2>&1; then
echo "ERROR: current directory is not a git repo" >&2
exit 1
fi
if [ -z "$GITLAB_API_PRIVATE_TOKEN" ]; then
echo "ERROR: private token not found" >&2
echo "Please set GITLAB_API_PRIVATE_TOKEN and try again" >&2
echo "Hint: visit https://gitlab.com/profile/personal_access_tokens" >&2
exit 1
fi
if [ -n "$GITLAB_REMOTE" ]; then
REMOTE=$GITLAB_REMOTE
elif git remote | grep gitlab >/dev/null 2>&1; then
REMOTE=gitlab
elif git remote | grep origin >/dev/null 2>&1; then
REMOTE=origin
else
echo "ERROR: no suitable branch found. Checked 'gitlab' and 'origin'." >&2
echo "Try setting GITLAB_REMOTE variable to remote name and try again." >&2
exit 1
fi
if ! [ -x "$(command -v jq)" ]; then
echo 'ERROR: jq JSON parser required but not found. See https://stedolan.github.io/jq/' >&2
exit 1
fi
PROJECT=$(git remote get-url $REMOTE | sed -Ee 's/.*:(.+)\.git/\1/')
PROJECT_ENCODED=$(echo $PROJECT | sed -Ee 's/\//%2F/')
BRANCH=$(git rev-parse --abbrev-ref HEAD)
# we could also use HEAD so long as no local commits have been made since push
SHA=$(git rev-parse $REMOTE/$BRANCH)
echo "Status of last pipeline for $PROJECT on $REMOTE/$BRANCH:" >&2
JSON=$(curl --header "PRIVATE-TOKEN: $GITLAB_API_PRIVATE_TOKEN" "https://gitlab.com/api/v4/projects/$PROJECT_ENCODED/repository/commits/$SHA" 2> /dev/null)
echo $JSON | jq .last_pipeline.status
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment