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:
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.
Update 2019–07: If you want the overall Cloud Build result to reflect the status of the relevant steps (instead of always showing “SUCCESS”), you can capture the result of a step and defer it until the end. Here’s an example:
Sample code is available at https://github.com/davidstanke/gcb-alwayspass
h/t to codrienne who taught me this trick!
tip: Want to monitor test results and take action on them? Check out this cool Cloud Function by dinagraves,