Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get git commit SHA within Jenkins pipeline with JGit

I have a Jenkins with the Github organization plugin that scans my organization and build all the branches/PRs of all the repositories within the organization that have a Jenkinsfile.

It works great, but I would like to retrieve for each build the commit SHA, in order to tag Docker images with both the branch name and the commit SHA.

Getting the branch name works great with env.BRANCH_NAME, however I cannot find any way to get the commit SHA.

The catch is that we are using JGit, so I cannot use git log to retrieve it.

I tried having a look at what is contained in the ENV using sh 'printenv', but there's nothing of any use there.

I also tried the following:

def checkoutResults = checkout scm
echo 'checkout results: ' + checkoutResults

but this yields the following result:

checkout results: [:]

Even though I cannot get the revision from my pipeline, Jenkins is getting it alright, as I can see in the logs:

...
Obtained Jenkinsfile from 98062e5f651ca698f4303c3bb8d20665ce491294
...
Checking out Revision 98062e5f651ca698f4303c3bb8d20665ce491294 (docker)

I am running the following versions:

  • Jenkins 2.73.3
  • Git plugin plugin 3.3.0
  • Pipeline: SCM Step plugin 2.6

Would appreciate any help in retrieving the commit SHA / revision in this particular situation.

like image 338
gotson Avatar asked Nov 15 '25 19:11

gotson


2 Answers

The git plugin did not include the fix until the 3.3.2 release. You'll need to update to at least git plugin 3.3.2.

The current git plugin release as of 23 Nov 2017 is 3.6.4. It includes significant additions and changes for multi-branch pipelines.

There is also a known bug in the reporting of NAME and EMAIL values which has a regression test that confirms the bug affects all implementations (git and jgit). You can use that regression test as an example of using those values if needed.

If you cannot update from git plugin 3.3.0 to 3.3.2, you may be able to use the JGit classes from within the pipeline script to perform the same type of query as was offered with command line git in another answer to the question. I have never done it, but I believe it is possible.

like image 74
Mark Waite Avatar answered Nov 18 '25 08:11

Mark Waite


I created a small groovy function

def getCommitSha(){
    return sh(returnStdout: true, script: 'git rev-parse HEAD')
}

you can add it to your pipeline , or to your shared library if you are using one ( if not it's a good time to start ... :-) )

like image 38
Mor Lajb Avatar answered Nov 18 '25 08:11

Mor Lajb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!