Terminate a buildspec early based on Condition, specifically on a git tag

Viewed 5557

I'd like to run my build pipeline only when my repo is tagged with certain specific release tags. I can get the tag value from the CODEBUILD_WEBHOOK_TRIGGER environment variable and I can conditionally execute code in my BUILD phase with some bash kung fu :

build:
  commands:
    - echo ${CODEBUILD_WEBHOOK_TRIGGER##*/}
    - |
     if expr "${CODEBUILD_WEBHOOK_TRIGGER}" : '^tag/30' >/dev/null; then 
        git add *
        git commit -am "System commit"
        git push
        git tag ${CODEBUILD_WEBHOOK_TRIGGER##*/}
        git push origin ${CODEBUILD_WEBHOOK_TRIGGER##*/}
        echo Pushed the repo
     fi

Works fine, I only push when a tag looks a certain way.

Putting aside the brittleness of the above, what I really want to do is to terminate the entire build process in the INSTALL phase if my CODEBUILD_WEBHOOK_TRIGGER variable doesn't have a specific prefix. I'd like to skip all subsequent steps and exit the pipeline without error.

Is there a way to do this? It would be nice to minimize the resources I'm using.

3 Answers

It worked for me to use the aws-cli command for stopping the build, using the provided CodeBuild environment variable ${CODEBUILD_BUILD_ID}:

- aws codebuild stop-build --id ${CODEBUILD_BUILD_ID}

For instance:

- |
    if expr "${CODEBUILD_WEBHOOK_TRIGGER}" : '^tag/30' >/dev/null; then 
        . . .
    else
        aws codebuild stop-build --id ${CODEBUILD_BUILD_ID}
    fi

Answering my own question, It turns out you can do this by specifying a branch filter in the source set up. The regular expression appears to match anything that comes back from the webhook:

^tag/30

That works for my tag pattern.

The question stands. I can still imagine use cases where you want to short-circuit the execution of the build pipeline for some other reason.

Related