Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 297
NateW Avatar asked Jun 27 '16 01:06

NateW


People also ask

How do I get environment variables in Groovy Jenkins?

In "Manage Jenkins" -> "Configure System" -> "Global Properties" -> "Environment Variables" I added "ALL_NODES_ENVVAR".

How do you call an environment variable in Jenkinsfile?

Jenkins Environment Variable is a global variable exposed through the env variable and used anywhere in the Jenkins file. Any value stored in the env variable gets stored as a String type. Environment Variables can be set either at the pipeline top level, at the specific stage level, or inside the script block.

How do I set environment variables in Groovy?

Download a binary distribution of Groovy and unpack it into some folder on your local file system. Set your GROOVY_HOME environment variable to the directory where you unpacked the distribution. Add GROOVY_HOME/bin to your PATH environment variable. Set your JAVA_HOME environment variable to point to your JDK.


1 Answers

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}"
}
like image 145
Konrad Kleine Avatar answered Oct 09 '22 07:10

Konrad Kleine