Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access git branch name from pipeline job?

I have a Jenkins Pipeline job which is configured to checkout a git repo and a specific local branch.

How can i get the name of the local branch in my Jenkinsfile?

I tried to load the git jenkins plugin env properties but had no luck.

node {
  checkout scm
  echo "1 "+ env.GIT_LOCAL_BRANCH
  echo "2 "+ env.GIT_BRANCH
}

Both values are "null"

like image 590
Jotschi Avatar asked Sep 20 '16 08:09

Jotschi


People also ask

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 Git branch name?

A branch in Git is simply a lightweight movable pointer to one of these commits. The default branch name in Git is master . As you start making commits, you're given a master branch that points to the last commit you made. Every time you commit, the master branch pointer moves forward automatically.


3 Answers

I found that I can capture the return value from checkout scm and use that to get the branch name (and other values)

  def scmVars

  node('api-sample-build') {
    stage('Clone source code') {
        scmVars = checkout scm
        // scmVars contains the following values
        // GIT_BRANCH=origin/mybranch
        // GIT_COMMIT=fc8279a107ebaf806f2e310fce15a7a54238eb71
        // GIT_PREVIOUS_COMMIT=6f2e319a1fc82707ebaf800fce15a7a54238eb71
        // GIT_PREVIOUS_SUCCESSFUL_COMMIT=310fce159a1fc82707ebaf806f2ea7a54238eb71
        // GIT_URL=https://stash.someworkplace.com/scm/poc/api-sample.git
    }
    stage('test scope') {
      echo scmVars.GIT_BRANCH
    }
  }

By defining the variable outside the node it is available in stages after the checkout.

like image 98
Daniel Watrous Avatar answered Oct 21 '22 03:10

Daniel Watrous


I'm now using the sh call to get the branch name. This requires at least version 2.4 of the Pipeline Nodes and Processes Plugin.

def branchName = sh(returnStdout: true, script: 'git rev-parse --abbrev-ref HEAD').trim()
echo branchName
like image 4
Jotschi Avatar answered Oct 21 '22 05:10

Jotschi


You can use scm attributes to get the list of branches configured for your scm :

// List of all configured branches
def allBranches = scm.branches

// Only the first configured branch name
def gitBranch = scm.branches[0].name
like image 1
Pom12 Avatar answered Oct 21 '22 05:10

Pom12