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
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}"