观察结果:
詹金斯文件
pipeline {
agent { node 'master' }
stages {
stage('Hello') {
steps {
echo env.GIT_COMMIT
}
}
}
}
输出:
[Pipeline] }
[Pipeline] // stage
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Hello)
[Pipeline] echo
e5b4b2deed1c8db486cef5641ef14c61fd48f9ed
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
詹金斯文件
pipeline {
agent { node 'master' }
options {
skipDefaultCheckout(true)
}
stages {
stage('Hello') {
steps {
checkout([$class: 'GitSCM', branches: [[name: '*/master']], extensions: [], userRemoteConfigs: [[url: '/tmp/r']]])
echo env.GIT_COMMIT
}
}
}
}
输出:
[Pipeline] node
Running on Jenkins in /var/jenkins_home/workspace/HelloWorld_master
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Hello)
[Pipeline] checkout
Selected Git installation does not exist. Using Default
The recommended git tool is: NONE
No credentials specified
> git rev-parse --resolve-git-dir /var/jenkins_home/workspace/HelloWorld_master/.git # timeout=10
Fetching changes from the remote Git repository
> git config remote.origin.url /tmp/r # timeout=10
Fetching upstream changes from /tmp/r
> git --version # timeout=10
> git --version # 'git version 2.30.2'
> git fetch --tags --force --progress -- /tmp/r +refs/heads/*:refs/remotes/origin/* # timeout=10
> git rev-parse refs/remotes/origin/master^{commit} # timeout=10
Checking out Revision e5b4b2deed1c8db486cef5641ef14c61fd48f9ed (refs/remotes/origin/master)
> git config core.sparsecheckout # timeout=10
> git checkout -f e5b4b2deed1c8db486cef5641ef14c61fd48f9ed # timeout=10
Commit message: "init"
First time build. Skipping changelog.
[Pipeline] echo
null
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
问题:
我使用的是jenkins版本2.349,该项目是多分支管道类型。
正如我在 Jenkins git 插件的 page 上读到的那样,它应该注入环境变量,但似乎只有在不跳过默认签出时才会执行,但在我们显式签出时则不会。我只能找到通过使用 script { } 块来访问这些 SCM 值(在我的例子中为 GIT_COMMIT)的方法。有没有办法在不跳入脚本块的情况下获取这些变量?
checkout() 调用返回一个具有 commit 属性的对象:
def result = checkout(...)
echo "Commit: ${result.GIT_COMMIT}"
请注意,这可能取决于安装的 git 插件的版本。