Search code examples
gitjenkinsgroovyjenkins-pipeline

Not able to read Git Environment variables Jenkins using Groovy Jenkinsfile


The Git Plugin is installed (by default) in my Jenkins but I'm unable to get the env variables that are supposed to be passed in by the Git Plugin. I'm looking for:

GIT_COMMIT
GIT_BRANCH
GIT_PREVIOUS_COMMIT 
GIT_PREVIOUS_SUCCESSFUL_COMMIT
GIT_URL

etc. I'm using the Pipeline Job Item that's pointing at a Github repo with the Jenkinsfile with the following code

stage 'PushToProd'
node {
    git url: "https://github.com/username/fakeurl.git"
    echo "Starting PushToProd"
    sh 'printenv'
    sh 'env'
    sh 'echo $BRANCH_NAME' 
    sh 'echo $GIT_COMMIT'
}

I'm getting plenty of environment variables when I use env or printenv just not the Github plugin ones.
Any tips on how I can get the Git env variables passed in to the job?

Update: I'm able to easily get the Git env variables when I use a Freestyle Project and have a shell step use echo $GIT_COMMIT. Still want to know though how to get it to work using Jenkinsfile + Pipeline job item.


Solution

  • This won't work due to lack of double quotes, missing curly braces, and missing env.:

    sh 'echo $BRANCH_NAME' 
    

    This works as expected in a Jenkinsfile:

    node {
        sh "echo ${env.BRANCH_NAME}"
    }