Introduction

AWS CodeBuild is a managed service from Amazon Web Services (AWS) that allows developers to build applications without having to manage servers. This makes it easier for them to build, test and deploy their services.

Developers can define their build specification (buildspec) using a collection of commands and settings in a YAML file. This file is called buildspec.yaml and is stored in the root of the source code repository. The buildspec.yaml file defines the build environment, the build commands, and the build artifacts. You can read more about the buildspec.yaml file here.

In this tutorial, we will look into how you can detect a failure during the Build phase of your CodeBuild build and stop the execution of the build.

What are the different phases during a CodeBuild build?

CodeBuild builds are divided into different phases. These phases are:

  • Install: This phase is used to install any dependencies required for the build. This phase is optional.
  • PreBuild: This phase is used to perform any pre-build steps. This phase is optional.
  • Build: This phase is used to build the application. This phase is mandatory.
  • PostBuild: This phase is used to perform any post-build steps. This phase is optional.

This how the build transitions through the different phases:

CodeBuild Build Phases

The PostBuild phase is executed even if the Build phase fails. This is because the PostBuild phase is used to perform any post-build steps. These steps are usually used to perform any cleanup tasks.

How to detect build failure in PostBuild phase?

If you want to detect a build failure in the PostBuild phase, you can use the CODEBUILD_BUILD_SUCCEEDING environment variable. This environment variable is set to 0 if the build fails and 1 if the build succeeds.

For example, if you want to exit the build if the build fails, you can use the following command:


  post_build:
    commands:
      - '[ ${CODEBUILD_BUILD_SUCCEEDING:-0} -eq 1 ] || exit 1'
      - echo "Build succeeded..."

Conclusion

In this tutorial, we looked at how you can detect a build failure in the PostBuild phase of your CodeBuild build. We also looked at how you can stop the execution of the build if the build fails.