Deploy new builds from Gitlab without exposing your instances security using this simple bash script. It scans the API for a new build, download the latest then executes the deploy.sh script inside of the build. Make sure you have jq installed before you continue.
#!/usr/bin/env bash
set -euo pipefail
cd `dirname $0`
#Project ID
PROJECT=827639846934
#https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html
PRIVATE_TOKEN=-BDlsq86JKHsndiwhD24
BASE_URL=https://gitlab.com
touch /root/deployed_build
DEPLOYED_BUILD=$(cat /root/deployed_build)
OUT_FILE=/tmp/build.tar.bz2
# lock it
PIDFILE="/tmp/$(basename "${BASH_SOURCE[0]%.*}.pid")"
exec 200>${PIDFILE}
flock -n 200 || ( echo "${BASH_SOURCE[0]} script is already running. Aborting . ." && exit 1 )
PID=$$
echo ${PID} 1>&200
if [ "${1-}" ]; then
LAST_SUCCESSFUL_BUILD="$1"
else
LAST_SUCCESSFUL_BUILD=$(curl -s -H "PRIVATE-TOKEN: ${PRIVATE_TOKEN}" "${BASE_URL}/api/v4/projects/${PROJECT}/jobs?per_page=1&scope[]=success" | jq -c '.[0] | .id')
fi
OUT_DIR="/tmp/build_${LAST_SUCCESSFUL_BUILD}"
download_latest() {
curl -fksSL -o ${OUT_FILE} -H "PRIVATE-TOKEN: ${PRIVATE_TOKEN}" "${BASE_URL}/api/v4/projects/${PROJECT}/jobs/${LAST_SUCCESSFUL_BUILD}/artifacts/build.tar.bz2"
}
if [ "${DEPLOYED_BUILD}" == "${LAST_SUCCESSFUL_BUILD}" ]; then
echo "Build ${LAST_SUCCESSFUL_BUILD} already deployed"
exit 0
fi
rm -rf /tmp/build*
download_latest
rm -rf ${OUT_DIR}
mkdir -p ${OUT_DIR}
tar jxf ${OUT_FILE} --directory ${OUT_DIR}
${OUT_DIR}/deploy.sh $LAST_SUCCESSFUL_BUILD
if [ ! "${1-}" ]; then
echo ${LAST_SUCCESSFUL_BUILD} > /root/deployed_build
fi
rm -rf /tmp/build*
echo "Build ${LAST_SUCCESSFUL_BUILD} deployed successfully"