I'm struggling to access GIT variables in my Jenkins pipeline
I need to know what GIT branch it's been checked out inside some bash code in a stage of the pipeline. I will use this to create different output file names. My pipeline is declarative, not scripted, and I'm using Jenkins 2.150.1
I tried everything I could find online but it's mostly incomplete code or for scripted pipelines. Or simply I can't put the information together.
Give how much time I spent on this, it would be nice to have a full working example that uses a declarative pipeline.
This is what I tried so far:
#1
Run git inside sh
, but Jenkins checks out a commit, not a branch, resulting in a detached head
#2
Looking for environment variables from the shell, but there's none set related to GIT. This snippet
steps { sh 'echo $GIT_BRANCH' }
always returns empty. I then tried on Groovy:
steps { echo "${env.GIT_BRANCH}" }
prints null
.
#3
In the "Global Variable Reference" there is a bit that says:
SCM-specific variables such as GIT_COMMIT are not automatically defined as environment variables; rather you can use the return value of the checkout step.
I searched online how to do it and I put together this code:
pipeline { stages { stage('Build') { steps { def scmVars = checkout([...]) echo 'scm : the commit id is ' + scmVars.GIT_COMMIT } } } }
But it fails with an exception
#4
use an environment
command and try to obtain that value somehow
#5
looking for variables at other levels in the Jenkinsfile, but apparently I can do that only on scripted pipelines
#5
Tried to access the build url and API call, but I'm behing a proxy and this complicates things with the URL.
My Jenkinsfile
pipeline { stages { stage('Build') { steps { checkout([ $class: 'GitSCM', doGenerateSubmoduleConfigurations: false, userRemoteConfigs: [[ url: '...', credentialsId: '...' ]], branches: [ [name: '*/master'] ] ]) sh ''' #!/bin/bash -x echo $MY_GIT_BRANCH_THAT_I_CANT_FIND ''' } } } }