smart smart -4 years ago 132
Groovy Question

Jenkins job DSL: extract branch with last commit in groovy script

I'm using Jenkins for running jobs automatically. I'm using also Bitbucket Server as a version control system.

I set up my Jenkins job DSL on any changes in my Bitbucket repo(on each commit) using some groovy script for job creation:

job(jobName) {
steps {
// Doing some staff. Need name of branch where last commit was done
}
scm {
git('ssh://git@<my_git_host>/<my_project>/<my_repo>.git', '**')
}
triggers {
bitbucketPush()
scm ''
}


So, when I'm doing some commits into
my_repo
this job runs and I want to extract name of branch where commit was done. Is it possible to do it somehow?

P.S. on Jenkins side(UI) I can see name of branch for current execution, but I have no idea how to extract it on groovy side.

Answer Source

Basically, the branch information will be stored in the Environment Variables with ID "GIT_BRANCH" for each build, So there are lot ways to extract it.

you can simply add the following script

job(jobName) {
  steps {
       shell('''
               echo $GIT_BRANCH
             '''.stripIndent().trim())
            }
  scm {
      git('ssh://git@<my_git_host>/<my_project>/<my_repo>.git', '**')
  }
  triggers {
    bitbucketPush()
    scm ''
  }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download