Is there a way to know what the last built commit was on the current branch and pipeline?
We have many servers running builds from different branches at the same time on a few pipelines, and wanted to know at build start which was the last commit from that branch to be run on that pipeline.
Currently we git diff against the main development branch or HEAD, but this doesn’t give correct results, as branches drift apart, as well as we can push more than one commit at a time.
You can use our builds REST API for this.
It’d require an API Access Token with read_builds permission to be available via the environment variable $BUILDKITE_API_TOKEN.
A sample script that could be executed from the pipeline:
#!/usr/bin/env bash
set -euo pipefail
# Get last 2 successful builds from current branch
BUILDS=$(curl -sf -H "Authorization: Bearer ${BUILDKITE_API_TOKEN}" \
"https://api.buildkite.com/v2/organizations/${BUILDKITE_ORGANIZATION_SLUG}/pipelines/${BUILDKITE_PIPELINE_SLUG}/builds?branch=${BUILDKITE_BRANCH}&state=passed&per_page=2")
CURRENT_BUILD_NUM="${BUILDKITE_BUILD_NUMBER}"
FIRST_BUILD_NUM=$(echo "$BUILDS" | jq -r '.[0].number')
FIRST_COMMIT=$(echo "$BUILDS" | jq -r '.[0].commit')
SECOND_COMMIT=$(echo "$BUILDS" | jq -r '.[1].commit // empty')
if [ "$CURRENT_BUILD_NUM" = "$FIRST_BUILD_NUM" ] && [ -n "$SECOND_COMMIT" ]; then
LAST_COMMIT="$SECOND_COMMIT"
else
LAST_COMMIT="$FIRST_COMMIT"
fi
echo "Current commit: ${BUILDKITE_COMMIT}"
echo "Last successful commit: ${LAST_COMMIT}"
echo "Commits since last build:"
git log --oneline "${LAST_COMMIT}".."${BUILDKITE_COMMIT}"