简体   繁体   中英

AWS Codecommit - Codebuild pass branch name to buildspec.yml

I'm using codecommit, codebuild and codepipeline so that each time I commit on a branch, the associated pipeline build from codecommit in codebuild (and then deployment / invalidation)

I have 3 different scripts in my package.json called build-master, build-test & build-prod, associated to the 3 branches respectively master, test & prod.

# buildspec.yml
phases:
  install:
    commands:
    - yarn --dev
  pre_build:
    commands:
    - aws configure set preview.cloudfront true
    - bash -c 'echo "Build started `date` on bucket s3://xx.xxxxxx.$CODEBUILD_SOURCE_VERSION.web"'
  build:
    commands:
    - bash -c 'yarn build-$CODEBUILD_SOURCE_VERSION'
artifacts:
  files:
    - '**/*'
  base-directory: 'dist'
  name: xxxx-xxxx.$(date +%Y-%m-%d-%h-%M-%s).$(CODEBUILD_SOURCE_VERSION)

$CODEBUILD_SOURCE_VERSION gives me the arn of the pipeline. I've tried other variables provided by codebuild but to no avail.

I also tried to use bash -c to get the branch from git, but in codebuild I don't have access to the repo.

Is there a way to get the name of the branch with my current config?

您可以使用所需的环境变量为每个分支/管道设置不同的 CodeBuild 项目。

The root cause here is that you are trying to use the Codebuild configuration to determine who is triggering and what to build. And that configuration is not smart and not flexible to customize.

The correct way is to enable CodeCommit and CodeBuild notification, and let the notifcation send to SNS topic then Lambda, and use Lambda to analysis the event to determine what branch / commit id / tag to build from.

I happened to have an open source solution for this, https://github.com/MacHu-GWU/aws_ci_bot-project you are responsible to write a short python function using IF, ELSE logic to decide: "based on the given CodeCommit event, which branch I should build from". For example:

This solution is a comprehensive one for all kinds of unique requirements, I think what you want to do is a subset of what it can do.

This is an old post but hope this helps

pre_build:
    commands:
      - BRANCH=$(echo ${CODEBUILD_WEBHOOK_HEAD_REF} | cut -d "/" -f3-)
      - |
        if [ "${BRANCH}"  = "master" ] || [ "${BRANCH}" = "dev" ]; then
        ...

Still working on figuring out how to pass the branch to env/variables so that I can use it in the env/parameter-store to retrieve parameters from different paths with a single buildspec

Bye

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM