Make a Cloud Build Step That Always Succeeds

TL;DR: Use bash as your entrypoint and add || echo 'failed' to your command

Google’s Cloud Build (GCB) automation system is serverless and stateless — when the build fails, the process exits and all resources used are cleaned up. That’s great for cost management and preventing security holes, but sometimes you need to keep some state around, in order to figure out what happened. In this post, you’ll learn how to tell GCB to keep going after a step failure.

For our example, we’ll use the Maven build system, along with the popular Maven testing plugin, Surefire. When mvn test is run, Surefire outputs some of its findings to stdout, which is captured in GCB logs. But there’s a bunch more detail that can be found in generated files on disk. In the event of a failure, it sure would be nice to go look at all the diagnostic info in those files. The problem here is that GCB, in the name of efficiency, aborts a failed build immediately and disposes of the build environment. It simply floats away, like, um… a cloud.

Don’t stop. Keep building!

The trick is to make it so the step always appears to GCB as having succeeded, regardless of what happened. That means it needs to emit a 0 (“success”) as its exit code. To do so, we will wrap our Maven test step in an OR statement — since the second term of the statement will always return success, the entire step will always return success, no matter what happens in the Maven part. (We’ll also need to use the “breakout syntax” that we learned about in my last post.)

Here’s the code:

# cloudbuild.yaml example configuration for Google Cloud Build
steps:
# GCB will always treat this step as passing.
# This means the build will always continue to the next step.
- id: Build and Test with Maven
name: 'gcr.io/cloud-builders/mvn'
entrypoint: 'bash'
args:
- '-c'
- |
mvn surefire-report:report || echo 'maven failure'
# This step will always run, even if the build step fails
- id: Save Maven Surefire Report to GCS
name: 'gcr.io/cloud-builders/gsutil'
args:
[
'cp', '-r',
'./target/site/surefire-report.html',
'gs://gcb-alwayspass/surefire-html-reports/$BUILD_ID/report.html',
]

If the Maven tests succeed, we’ll have a report showing that everything passed, saved in Cloud Storage. But that’s boring. What’s useful is that, even if the tests fail, we’ll still get that report, and we can dig in to fix the code.

You can use this technique for any situation where you need to do something after a volatile step, regardless of that step’s outcome. Have you tried this method? Tell me what you did in the comments.

Sample code is available at https://github.com/davidstanke/gcb-alwayspass

h/t to codrienne who taught me this trick!