Reyansh Kharga
Reyansh Kharga

Reputation: 346

AWS Build Project succeeds even when a command fails in buildspec.yml

I'm using AWS CodeBuild to deploy the function to AWS lambda using serverless-framework.

Here is my buildspec.yml,

version: 0.2
phases:
  install:
    runtime-versions:
      nodejs: 10  
    commands:
      - echo installing Mocha...
      - npm install -g mocha
      - echo installing Serverless...
      - npm install -g serverless
  pre_build:
    commands:
      - echo running npm install for global project...
      - npm install
      - echo running npm install for each function...
      - folders=src/*
      - for value in $folders;
        do
          echo $value
          npm --prefix $value install $value;
        done
  build:
    commands:
      - sls package
      - serverless deploy --stage $STAGE --region $AWS_DEFAULT_REGION | tee deploy.out
  post_build:
    commands:
      - echo done
      # - . ./test.sh

The problem is even when the serverless deploy --stage $STAGE --region $AWS_DEFAULT_REGION | tee deploy.out command fails, the build project is shown as success by AWS codebuild in the codepipeline.

I want the build status as failure when serverless deploy command fails.

Upvotes: 2

Views: 2509

Answers (2)

shariqmaws
shariqmaws

Reputation: 8890

Your command:

- serverless deploy --stage $STAGE --region $AWS_DEFAULT_REGION | tee deploy.out

... is not returning a non-zero code on failure which is required to fail the build. The command tee is masking the return code from serverless deploy as it itself is responding with a '0' return code.

I would recommend to re-write the command as:

- serverless deploy --stage $STAGE --region $AWS_DEFAULT_REGION > deploy.out
- cat deploy.out

Upvotes: 2

Marcin
Marcin

Reputation: 238727

This happens because post_build executes whether build fails or succeeds. Thus it does not meter that build fails, post_build will run anyway. This is explained in the build phase transitions.

You can rectify this by "manually" checking if build failed in post_build by checking CODEBUILD_BUILD_SUCCEEDING env variable:

  • CODEBUILD_BUILD_SUCCEEDING: Whether the current build is succeeding. Set to 0 if the build is failing, or 1 if the build is succeeding.

Thus in your post_build you can check ifCODEBUILD_BUILD_SUCCEEDING == 0 and exit 1 if is true.

  post_build:
    commands:
      - if [[ $CODEBUILD_BUILD_SUCCEEDING == 0 ]]; then exit 1; fi
      - echo done
      # - . ./test.sh

Upvotes: 3

Related Questions