@Lazy似乎没有在Jenkins管道中的第一次调用时返回值。知道为什么?
码:
class JenkinsStatus implements Serializable {
def pipeline
@Lazy String author = {
this.pipeline.echo "Call to Author"
def commit = this.pipeline.sh(returnStdout: true, script: 'git rev-parse HEAD')
def a = this.pipeline.sh(returnStdout: true, script: "git --no-pager show -s --format='%an' ${commit}").trim()
this.pipeline.echo("inside Author is: ${a}")
a
}()
}
pipeline {
agent any
stages {
stage( "Checkout repo") {
steps {
// SCM checkout() here.
}
}
}
post {
always {
script {
JenkinsStatus jstatus = [
pipeline: this
]
echo "Author1: ${jstatus.author}"
echo "Author2: ${jstatus.author}"
}
}
}
}
当我运行管道时,我得到以下结果:
Call to Author
[Pipeline] sh
+ git rev-parse HEAD
[Pipeline] sh
+ git --no-pager show -s --format=%an 9242efd51b83b4202863a04ac0b3c45c256a3948
[Pipeline] echo
inside Author is: <edit out>
[Pipeline] echo
Author1: null
[Pipeline] echo
Author2: <edit out>
你可以清楚地看到a
的定义。这是回归。但JenkinsStatus.author直到第二次调用才实际应用。
Jenkins CPS转换使用Groovy注释做了有趣的事情。我从来没有能够让@Lazy
使用共享库类中的字段。如果在整个运行时只有一个类,则@Singleton
可以工作,但是每当你添加第二个类时都会失败。 @Delegate
根本不起作用。
FWIW,对于一个非常相似的问题,这是一个公认的答案:https://stackoverflow.com/a/54590943/6498020
这是一个众所周知的詹金斯问题:JENKINS-45901
这已于2017年8月开放。看起来它不会很快修复:
不确定是否有任何特定的地方Groovy语言支持(或缺乏),但无论如何我不希望这个问题或类似的任何问题得到解决。未来的重点是允许外部流程执行,而不是在CPS引擎上浪费更多时间,除非出现安全漏洞或严重的回归。