Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get git branch name in Jenkins Pipeline/Jenkinsfile

I've create a jenkins pipeline and it is pulling the pipeline script from scm.
I set the branch specifier to 'all', so it builds on any change to any branch.

How do I access the branch name causing this build from the Jenkinsfile?

Everything I have tried echos out null except

sh(returnStdout: true, script: 'git rev-parse --abbrev-ref HEAD').trim() 

which is always master.

like image 925
Alex Yurkowski Avatar asked Feb 22 '17 05:02

Alex Yurkowski


People also ask

How do I pass a Jenkins branch name?

Give any Name e.g. BRANCH select parameter type as "Branch" and put default value for branch. Then in Branches to build inthat put ${BRANCH}. Build job with parameter as branch name...

How do I pass a Git branch as parameter in Jenkins?

If you want to be able to dynamically give a Git branch to use in a Jenkins build then you'll need to do a couple of things. Then, in your Pipeline configuration, under Branches to build, add your parameter name inside the Branch Specifier box, surrounded by ${} . Jenkins will expand your variable when the job runs.

What is branch name in Git?

In Git, branches are commonly used in order to have a development separated from your main workflow. In software engineering teams, it is quite common to have a specific workflow implemented. You may choose for example to have one branch per major release or to have a branch in order to quickfix an issue.


1 Answers

Use multibranch pipeline job type, not the plain pipeline job type. The multibranch pipeline jobs do posess the environment variable env.BRANCH_NAME which describes the branch.

In my script..

stage('Build') {     node {         echo 'Pulling...' + env.BRANCH_NAME         checkout scm              } } 

Yields...

Pulling...master 
like image 177
James Avatar answered Oct 08 '22 01:10

James