Waiting for build to complete when invoked via HTTP API

api

#1

Hey do you have any best practices for waiting on an build that was invoked via the HTTP API?

We’re using CircleCI to power our Prod -> Stage DB copy job and using a secondary job to do the invoking but in order to complete this job it needs to call two other jobs (x1 for our Infrastructure deploy & x1 for our application deploy). Is even using the HTTP API the best practice in this scenario? Is there a way to call another job as a step and have it wait on the success of that job before proceeding?


Can I trigger a build via API and wait for it to complete?
#2

For now I’ve written a little polling function in bash to do the job.

wait_for_build() {
    CIRCLE_API_TOKEN=$1
    BUILD_URL=$2
    TIMEOUT_IN_SECS=$3
    POLL_INTERVAL_IN_SECS=15

    # Pipe syserr message to /dev/null, we don't care we're not trying to change the system date.
    # Use cat to suppress exit code.
    timeout_time=$(date -s "${TIMEOUT_IN_SECS} seconds" +%s 2> /dev/null | cat)
    for i in `seq 1 $(($TIMEOUT_IN_SECS / $POLL_INTERVAL_IN_SECS))`; do
        echo "[Try ${i}] Waiting for build: $BUILD_URL"

        result=$(curl --user ${CIRCLE_API_TOKEN}: \
            --fail \
            $BUILD_URL)
        lifecycle=$(echo $result | jq --raw-output --exit-status '.lifecycle')
        if [ $lifecycle == 'finished' ]; then
            # We've got to a final state, eg. success, failed, canceled etc.
            break
        fi

        if [ $(date +%s) > timeout_time ]; then
            # We've hit a roadblock, let's get out of here and not tie things up any longer.
            break;
        fi
        
        sleep $POLL_INTERVAL_IN_SECS
    done
}

wait_for_build "<my api token>" "<my build url to check>" "<max timeout in secs>"

Does the job for what I need it to do for now.


#3

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.