How can I stop the execution when the codebuild is completed in bash?

Viewed 109

I am creating a script that starts a build in AWS Codebuild. In addition to running it, I would like that when the build completes (reaches the COMPLETED phase) and reads the string "COMPLETED", it stops.

This is the script:

#!/bin/bash
# Deploy API Gateway Authorizer

BUILD_PROJECT=$1
ENVIRONMENT=$2

if [ -z "$BUILD_PROJECT" ]
then
    echo "BUILD_PROJECT is empty, exiting...."
    exit 1
fi

if [ -z "$ENVIRONMENT" ]
then
    echo "ENVIRONMENT is empty, exiting...."
    exit 1
fi

function getStatus {
    id=$(aws codebuild list-builds-for-project --project-name "${BUILD_PROJECT}-${ENVIRONMENT}" | jq -r '.ids[0]')
    aws codebuild batch-get-builds --ids "$id" | jq '.builds[].phases[] | select (.phaseType=="COMPLETED") | .phaseType'
}

echo "----------------------------------------------------"
echo "Deploying: ${BUILD_PROJECT}-${ENVIRONMENT}"
echo "----------------------------------------------------"
aws codebuild start-build --project-name "${BUILD_PROJECT}-${ENVIRONMENT}"

while [ getStatus != "COMPLETED" ]
do
    echo "Deploying..."
    sleep 5
    getStatus
done 

I have tried this with a getStatus function and then inside a while loop until the result of the function != "COMPLETED" but even though it shows COMPLETED in the console output, it always keeps executing.

This is a console output when I run the script, for example:

----------------------------------------------------
Deploying: api-gateway-authorizer-us2-stage
----------------------------------------------------
Deploying...
Deploying...
Deploying...
Deploying...
Deploying...
Deploying...
Deploying...
Deploying...
Deploying...
Deploying...
Deploying...
Deploying...
Deploying...
Deploying...
"COMPLETED"
Deploying...
"COMPLETED"
Deploying...
"COMPLETED"
Deploying...
"COMPLETED"
Deploying...
1 Answers

Your COMPLETE is actually "COMPLETE" because you do not use -r flag in jq. Also you have to wrap your getStatus as $(getStatus) and use [[ in loop:

#!/bin/bash
# Deploy API Gateway Authorizer

BUILD_PROJECT=$1
ENVIRONMENT=$2

if [ -z "$BUILD_PROJECT" ]
then
    echo "BUILD_PROJECT is empty, exiting...."
    exit 1
fi

if [ -z "$ENVIRONMENT" ]
then
    echo "ENVIRONMENT is empty, exiting...."
    exit 1
fi

function getStatus {
    id=$(aws codebuild list-builds-for-project --project-name "${BUILD_PROJECT}-${ENVIRONMENT}" | jq -r '.ids[0]')
    aws codebuild batch-get-builds --ids "$id" | jq -r '.builds[].phases[] | select (.phaseType=="COMPLETED") | .phaseType'
}

echo "----------------------------------------------------"
echo "Deploying: ${BUILD_PROJECT}-${ENVIRONMENT}"
echo "----------------------------------------------------"
aws codebuild start-build --project-name "${BUILD_PROJECT}-${ENVIRONMENT}"

while [[ $(getStatus) != "COMPLETED" ]]
do
    echo "Deploying..."
    sleep 5
    getStatus
done 
Related