Detecting Failure or Success in AWS Code Build

AWS
Web Dev

Mon May 08 2023

Problem

At Develop Right we recently ran into a problem where our AWS CodeBuild pipeline which is used to publish assets to S3 for Cloudfront was failing. Unfortunately, do to the lack of visiblity into these issues the issue went unnoticed for a while. This meant no updates to the site were published. 

After looking into it, a quick fix was made to have visibility via Slack to see whether the Build part of Code Pipeline has passed or failed. 

Solution

If you want have specific code that runs based on whether the Build Phase of Code Build is passing or failing you can modify the post_build phase to detect whether the previous stages are succeeding using an Environment variable. 

 

The environment variable "CODEBUILD_BUILD_SUCCEEDING" is set to 1 if it is succeeding and 0 if it is failing. 

Within the post_build phase of the buildspec template you use with Code Build the environment will be available to be used and it will tell you whether the previous build phase has completed successfully. 

 

A quick solution to have specific code run based on whether it is successful or not is:

  post_build:
    commands:
      - bash -c "if [ '$CODEBUILD_BUILD_SUCCEEDING' == '0' ]; then echo 'Build Failed'; else echo 'Build Success'; fi"

 

For Develop Right we use the conditions to publish messages to Slack stating if the build failed or not. 

  post_build:
    commands:
      - bash -c "if [ '$CODEBUILD_BUILD_SUCCEEDING' == '0' ]; then ./scripts/create-release-message.sh $SLACK_API_HOOK 'Build Failed'; else ./scripts/create-release-message.sh $SLACK_API_HOOK 'Build Success'; fi"