The Full clone that CodePipeline does leaves the local repository .git
in a detached HEAD state, meaning that in order to get the branch name you will have to either get it with the help of CodeBuild environment variables to retrieve it from CodePipeline, or to execute the following command (either in your buildspec.yml
or later in Elastic Beanstalk, if that's what you're using after deployment):
git branch -a --contains HEAD | sed -n 2p | awk '{ printf $1 }'
If you want to go with the CodeBuild environment variables option, then navigate to:
CodePipeline -> Edit: Build -> Environment variables - optional
and add BranchName
: #{SourceVariables.BranchName}
as Plaintext
Then, in your buildspec.yml
code you can do the following:
version: 0.2
phases:
build:
commands:
- echo Branch - $BranchName
- echo Commit - $CommitId
- echo Checking out branch - $BranchName
- git checkout $BranchName
artifacts:
files:
- '**/*'
The above will print:
Branch - master
Commit - f4f78b319c308600eab015a5d6529add21660dc1
Checking out branch - master
PS 1: The Environment Variables must be set from CodePipeline -> Edit: Build -> Environment variables - optional
. If you set these variables in CodeBuild -> Edit -> Environment -> Additional configuration -> Environment variables
it WON'T WORK! This is so dumb, but I spent too much time on this myself.
PS 2: For a bigger list of Environment variables during CodeBuild, see Variables List, Action Variables, and CodeBuild variables.