Git Variables in Jenkins Workflow plugin

Depending on the SCM plugin you are using, the checkout step may return additional information about the revision. This was resolved in JENKINS-26100. It was released in the 2.6 version of the workflow-scm-step plugin.

For example, using the Git plugin, you can do something like:

final scmVars = checkout(scm)
echo "scmVars: ${scmVars}"
echo "scmVars.GIT_COMMIT: ${scmVars.GIT_COMMIT}"
echo "scmVars.GIT_BRANCH: ${scmVars.GIT_BRANCH}"

This will vary depending on the plugin you use, so the original answer may work better for you.


Original Answer

With the 2.4 release of the Pipeline Nodes and Processes Plugin, you can simply do:

def gitCommit = sh(returnStdout: true, script: 'git rev-parse HEAD').trim()

This is what I'm doing, based on the example provided in the Jenkins examples repo:

node {
    git url: 'https://git.com/myproject.git'

    sh 'git rev-parse --abbrev-ref HEAD > GIT_BRANCH'
    git_branch = readFile('GIT_BRANCH').trim()
    echo git_branch

    sh 'git rev-parse HEAD > GIT_COMMIT'
    git_commit = readFile('GIT_COMMIT').trim()
    echo git_commit
}

Edit you can do this shorter via

git_commit = sh(returnStdout: true, script: "git rev-parse HEAD").trim()

Depending on the information you need, there is a very straightforward solution: get the "checkout scm" operation return: it provides GIT_BRANCH, GIT_COMMIT, GIT_PREVIOUS_COMMIT, GIT_PREVIOUS_SUCCESSFUL_COMMIT and GIT_URL.

node { 
    stage ("Checkout") {

        scmInfo = checkout scm

        /*...*/
        echo "scm : ${scmInfo}"
        echo "${scmInfo.GIT_COMMIT}"


    }
}

This will output:

...
[Pipeline] echo
    scm : [GIT_BRANCH:my-branch, GIT_COMMIT:0123456789abcdefabcdef0123456789abcdef01, GIT_PREVIOUS_COMMIT:aaaabbbcccdddeeeefffe0123456789012345678, GIT_PREVIOUS_SUCCESSFUL_COMMIT:aaaabbbcccdddeeeefffe0123456789012345678, GIT_URL:http://my.si.te/my-repository.git]
[Pipeline] echo
    0123456789abcdefabcdef0123456789abcdef01
...

More details here Jenkins Pipeline SCM Steps