Using GIT variables in a declarative Jenkins pipeline
Solution 1:
Finally I found an example and I was able to understand how to do this.
I need to use a script command, obtain the Map
returned by checkout
and save the Map
as environment variable:
stage('Checkout code') {
steps {
script {
// Checkout the repository and save the resulting metadata
def scmVars = checkout([
$class: 'GitSCM',
...
])
// Display the variable using scmVars
echo "scmVars.GIT_COMMIT"
echo "${scmVars.GIT_COMMIT}"
// Displaying the variables saving it as environment variable
env.GIT_COMMIT = scmVars.GIT_COMMIT
echo "env.GIT_COMMIT"
echo "${env.GIT_COMMIT}"
}
// Here the metadata is available as environment variable
...
}
}
Solution 2:
Quoting the docs:
GIT_BRANCH
For Git-based projects, this variable contains the Git branch that was checked out for the build (normally origin/master)
Specifically for the Pipeline plugin, there's an answer to this problem on StackOverflow:
The env.BRANCH_NAME variable contains the branch name.
As of Pipeline Groovy Plugin 2.18, you can also just use BRANCH_NAME (env isn't required but still accepted.)
On some conditions, this variable may be empty, the following should fix this:
Add [$class: 'LocalBranch', localBranch: "**"] to “extentions” in your checkout step.