Skip to content

Instantly share code, notes, and snippets.

@orihomie
Created March 17, 2023 07:06
Show Gist options
  • Save orihomie/cfeb12b071a15d952fcabfcfc8dc65c9 to your computer and use it in GitHub Desktop.
Save orihomie/cfeb12b071a15d952fcabfcfc8dc65c9 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
JENKINS_URL="https://user:token@jenkins.domain" #"http://<jenkins-server>"
JENKINS_URI="/job/full/path" #"my-job"
# Trigger the job with parameters
RESPONSE_FILE=/tmp/$(uuidgen).txt
response_code=$(curl -I -X POST -so "$RESPONSE_FILE" -w "%{http_code}" "${JENKINS_URL}${JENKINS_URI}/build")
if [[ "$response_code" != "201" ]]; then
echo "Failed to trigger job";
exit 1;
fi
queue_url=$(cat $RESPONSE_FILE | grep Location | awk '{print $2}' | sed 's/http:\/\/jenkins\.domain//' | tr -d '\r')
# Wait for the job to start and get its queue item ID
RESPONSE_FILE=/tmp/$(uuidgen).txt
touch $RESPONSE_FILE
queue_item_id="";
set -x
while [[ -z ${queue_item_id} ]]; do
queue_response_code=$(curl -so "$RESPONSE_FILE" -w "%{http_code}" "${JENKINS_URL}${queue_url}api/json");
if [[ $queue_response_code == "404" ]]; then
echo "Job not found";
exit 1;
fi
if [[ $(cat $RESPONSE_FILE | jq -r '.executable') != "null" ]]; then
queue_item_id=$(cat $RESPONSE_FILE | jq -r '.id');
fi
sleep 1
done
# Wait for the job to complete and get its build ID
RESPONSE_FILE=/tmp/$(uuidgen).txt
BUILD_ID=""
while [[ -z ${BUILD_ID} ]]; do
queue_item_response_code=$(curl -so "$RESPONSE_FILE" -w "%{http_code}" "${JENKINS_URL}/queue/item/${queue_item_id}/api/json");
if [[ $queue_item_response_code == "404" ]]; then
echo "Job not found in queue";
exit 1;
fi
if [[ $(cat $RESPONSE_FILE | jq -r '.executable') != "null" ]]; then
BUILD_ID=$(cat $RESPONSE_FILE | jq -r '.executable.number');
fi
sleep 1
done
BUILD_STATUS=""
POLL_INTERVAL_SEC=3
while [[ "$BUILD_STATUS" != "SUCCESS" && "$BUILD_STATUS" != "FAILURE" && "$BUILD_STATUS" != "ABORTED"]]; do
sleep $POLL_INTERVAL_SEC;
BUILD_STATUS=$(curl -k -s -X GET ${JENKINS_URL}${JENKINS_URI}/${BUILD_ID}/api/json | jq -r '.result');
echo "Waiting for job to end...";
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment