|
| 1 | +#!/bin/bash |
| 2 | + |
| 3 | +error_exit() { |
| 4 | + echo "$1" 1>&2 |
| 5 | + exit 1 |
| 6 | +} |
| 7 | + |
| 8 | +PROJECT_NAME=$1 |
| 9 | +# get the source version to be built (defaults to main branch if not specified) |
| 10 | +SOURCE_VERSION=${2:-main} |
| 11 | + |
| 12 | +echo "Starting CodeBuild project ${PROJECT_NAME}" |
| 13 | + |
| 14 | +# dump all GITHUB_* environment variables to file and pass to start job |
| 15 | +jq -n 'env | to_entries | [.[] | select(.key | startswith("GITHUB_"))] | [.[] | {name: .key, value:.value, type:"PLAINTEXT"}]' >/tmp/gh_env_vars.json |
| 16 | + |
| 17 | +START_RESULT=$( |
| 18 | + aws codebuild start-build-batch \ |
| 19 | + --project-name ${PROJECT_NAME} \ |
| 20 | + --source-version $SOURCE_VERSION \ |
| 21 | + --environment-variables-override file:///tmp/gh_env_vars.json |
| 22 | +) |
| 23 | + |
| 24 | +if [ "$?" != "0" ]; then |
| 25 | + error_exit "Could not start project. Exiting." |
| 26 | +else |
| 27 | + echo "Build started successfully." |
| 28 | +fi |
| 29 | + |
| 30 | +BUILD_ID=$(echo ${START_RESULT} | jq '.buildBatch.id' -r) |
| 31 | +echo "Build id $BUILD_ID" |
| 32 | + |
| 33 | +BUILD_STATUS="IN_PROGRESS" |
| 34 | +while [ "$BUILD_STATUS" == "IN_PROGRESS" ]; do |
| 35 | + echo "Checking build status." |
| 36 | + BUILD=$(aws codebuild batch-get-build-batches --ids ${BUILD_ID}) |
| 37 | + BUILD_STATUS=$(echo $BUILD | jq '.buildBatches[0].buildBatchStatus' -r) |
| 38 | + |
| 39 | + JOBS=$(echo $BUILD | jq '.buildBatches[0].buildGroups | [.[] | {identifier: .identifier, status: .currentBuildSummary.buildStatus} | select(.identifier | startswith("JOB"))]') |
| 40 | + TOTAL_JOBS=$(echo $JOBS | jq 'length') |
| 41 | + |
| 42 | + SUCCEEDED_CNT=$(echo $JOBS | jq '[.[] | select(.status == "SUCCEEDED")] | length') |
| 43 | + IN_PROGRESS_CNT=$(echo $JOBS | jq '[.[] | select(.status == "IN_PROGRESS")] | length') |
| 44 | + |
| 45 | + FAILED_CNT=$(($TOTAL_JOBS - $SUCCEEDED_CNT - $IN_PROGRESS_CNT)) |
| 46 | + |
| 47 | + if [ "$BUILD_STATUS" == "IN_PROGRESS" ]; then |
| 48 | + echo "Build is still in progress (failed=$FAILED_CNT; in_progress=$IN_PROGRESS_CNT; succeeded=$SUCCEEDED_CNT; total=$TOTAL_JOBS), waiting..." |
| 49 | + |
| 50 | + fi |
| 51 | + sleep 10 |
| 52 | +done |
| 53 | + |
| 54 | +if [ "$BUILD_STATUS" != "SUCCEEDED" ]; then |
| 55 | + BUILD=$(aws codebuild batch-get-build-batches --ids ${BUILD_ID}) |
| 56 | + FAILED_BUILDS=$(echo $BUILD | jq '.buildBatches[0].buildGroups | [.[] | {identifier: .identifier, status: .currentBuildSummary.buildStatus} | select(.status == "FAILED")]') |
| 57 | + echo "Failed builds in batch" |
| 58 | + echo $FAILED_BUILDS |
| 59 | + error_exit "Build failed, please review job output" |
| 60 | +else |
| 61 | + echo "Build succeeded." |
| 62 | +fi |
0 commit comments