0

I have a monorepo set up and a cloudbuild.yaml file in the root of my repository spins off child cloud build jobs in the first step:

# Trigger builds for all packages in the repository.
  - name: "gcr.io/cloud-builders/gcloud"
    entrypoint: "bash"
    args: [
        "./scripts/cloudbuild/build-all.sh",
        # Child builds don't have the git context, so pass them the SHORT_SHA.
        "--substitutions=_TAG=$SHORT_SHA",
      ]
    timeout: 1200s # 20 minutes

The build all script is something I copied from the community builders repo:

#!/usr/bin/env bash
DIR_NAME="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

set -e # Sets mode to exit on an error, without executing the remaining commands.

for d in {packages,ops/helm,ops/pulumi}/*/; do
    config="${d}cloudbuild.yaml"
    if [[ ! -f "${config}" ]]; then
        continue
    fi

    echo "Building $d ... "
    (
        gcloud builds submit . --config=${config} $*
    ) &
done
wait

It waits until all child builds are done before continuing to the next one... handy!

Only problem is, if any of the child builds fail, it will still continue to the next step.

Is there a way to make this step fail if any of the child builds fail? I guess my script isn't returning the correct error code...?

Sebastian Nemeth
  • 5,505
  • 4
  • 26
  • 36

1 Answers1

0

The set -e flag should make the script to exit if any of the commands performed has an error, however you can also check the output of a command by using the $? variable, for example you can include the next lines:

echo "Building $d ... "
(
    gcloud builds submit . --config=${config} $*
    if [ $? == 1 ]; then #Check the status of the last command
       echo "There was an error while building $d, exiting"
       exit 1
    fi
) &

So if there was an error the script will exit and give an status of 1 (error)

Emmanuel
  • 1,436
  • 1
  • 11
  • 17
  • Hm I'm actually already using `set -e`. I think the problem is that `gcloud builds submit` doesn't return any exit code other than 0, even if a build fails. – Sebastian Nemeth Sep 10 '20 at 07:57
  • I tested the code provided before posting the answer, `gcloud submit` indeed returns an exit code of 1 at least when you fail to read the yaml file, which is what I simulated. However if you want update the post with an specific error so I can try to simulate it or even better use `echo $?` right after the `gcloud submit` command is performed to check the exit status of said command – Emmanuel Sep 10 '20 at 14:57
  • Were you able to test the script, did you get any output from the variable? – Emmanuel Sep 16 '20 at 22:07