Reputation: 763
I am trying to read some environment variables in Jenkins pipeline script that should be set by Git plugin, but it seems they are not set, because when I tried to use in script its value is empty string and also if I use sh 'printenv' I can see that they are not set.
Probably I am missing something but I cannot find what.
Any idea?
Upvotes: 12
Views: 6981
Reputation: 141
Since the git plugin works fine for declarative scripts you can use a declarative script to get the git environment variables and set them for the scripted section to use.
So in a nutshell:
pipeline {
environment {
gitCommit = "${env.GIT_COMMIT}"
}
agent {
label <agent>
}
stages {
stage('SetEnvironmentProperties') {
agent {
label <agent>
}
steps {
env.setProperty("GIT_COMMIT", "$gitCommit")
}
}
}
}
node(<agent>) {
echo "Using Git Commit Hash ${env.GIT_COMMIT}"
}
This is absolutely a hack, but it works for us. We're hoping that the issue get's resolved soon and we can simply remove the declarative section altogether.
I believe this works because this creates a Declarative: Checkout SCM stage
where the environment variables become accessible in subsequent pipeline stages. This is equivalent, I think, to what is described in this answer. What I'm not so clear on is why resetting them would persist them into the scripted stages. Which is why this is a hack...
Upvotes: 0
Reputation: 1087
If you were using checkout scm
like me you will notice that you don't have any GIT-RELATED environment variables to help you out so in this case, you need to do this:
scm_variables = checkout scm
echo scm_variables.get('GIT_COMMIT')
Upvotes: 6
Reputation: 5321
Per this page:
http://JenkinsURL/pipeline-syntax/globals:
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.
This is supposed to be resolved in Jenkins 2.60, I believe:
https://plugins.jenkins.io/pipeline-model-definition
See the item for JENKINS-45198
You can workaround by running the appropriate git commands in a shell and assigning them to a variable:
GIT_REVISION = sh( script: 'git rev-parse HEAD', returnStdout: true )
In a Declarative pipeline, you will have to wrap this in a script{} block, and probably declare the variable outside of your pipeline to get the appropriate scope.
Upvotes: 11