get GitHub git branch for AWS CodeBuild

前端 未结 5 1779
鱼传尺愫
鱼传尺愫 2021-02-07 08:15

I\'m setup AWS CodeBuild to build automatically from GitHub. Other CI services provide an environment variable for the branch, but I can\'t find one for AWS CodeBuild. There is

5条回答
  •  青春惊慌失措
    2021-02-07 08:37

    CodeBuild strips git information from the filesystem. There is no .git folder, so running a git command will be fruitless.

    I have added a parameter to my CI/CD CloudFormation template:

      GitBranch:
        Description: Github branch to be deployed
        Type: String
        Default: master
    

    And I have a Bash script that creates / updates the CI/CD stack:

    readonly git_branch=$(git branch 2>/dev/null | grep "^*" | colrm 1 2)
    
    aws cloudformation create-stack \
      --stack-name ${cicd_stack_name} \
      --parameters ParameterKey=GitBranch,ParameterValue=${git_branch}
    

    I then export the value as an environment variable to CodeBuild machine:

    CodeBuildProject:
    Type: AWS::CodeBuild::Project
    Properties:
      Environment:
        Type: LINUX_CONTAINER
        Image: aws/codebuild/java:openjdk-8
        EnvironmentVariables:
          - Name: GIT_BRANCH
            Value: !Ref GitBranch
    

    Now I have access to it in my buildspec.yml:

    post_build:
      commands:
        - echo [PHASE] Entered the post_build phase...
        - echo "[DEBUG] Git branch ${GIT_BRANCH}"
    

提交回复
热议问题