为了看到这是如何工作的,使用一个 GString 对象来执行 println 并同时返回 agentName 变量。从输出结果可以看出,在其他管道代码之前,这行代码已经成功地被评估了。
agentName = "Windows"
agentLabel = "${println 'Right Now the Agent Name is ' + agentName; return agentName}"
pipeline {
agent none
stages {
stage('Prep') {
steps {
script {
agentName = "Linux"
}
}
}
stage('Checking') {
steps {
script {
println agentLabel
println agentName
}
}
}
stage('Final') {
agent { label agentLabel }
steps {
script {
println agentLabel
println agentName
}
}
}
}
}
控制台输出(请注意,我实际上并没有在标记为Windows的此实例上安装node,所以在它找不到之后我中止了操作):
Started by user Admin
[Pipeline] echo
Right Now the Agent Name is Windows
[Pipeline] stage
[Pipeline] { (Prep)
[Pipeline] script
[Pipeline] {
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Checking)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
Windows
[Pipeline] echo
Linux
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Final)
[Pipeline] node
Still waiting to schedule task
There are no nodes with the label ‘Windows’
Aborted by Admin
[Pipeline] // node
[Pipeline] }
[Pipeline] // stage
[Pipeline] End of Pipeline
ERROR: Queue task was cancelled
Finished: ABORTED
请注意输出结果中出现的代码行Right Now the Agent Name is Windows
,它出现得非常早。这解释了为什么您的变量值为空。该语句在脚本修改变量之前很长时间就已经被评估了。
我可以尝试使用延迟加载的 GString
以稍后获取变量。
agentLabel = "${-> println 'Right Now the Agent Name is ' + agentName; return agentName}"
很不幸,这会引发错误,因为它期望的是一个字符串类型。显然,它可以自行将非惰性 GString 强制转换为字符串,但不能转换惰性版本。所以当我强制进行字符串转换时,它当然会在那个时候求值该变量(这再次发生在管道代码实际运行之前)。
agent { label agentLabel as String }
你可以通过返回旧的节点分配方法来解决这个问题:
agentName = "Windows"
agentLabel = "${-> println 'Right Now the Agent Name is ' + agentName; return agentName}"
pipeline {
agent none
stages {
stage('Prep') {
steps {
script {
agentName = "Linux"
}
}
}
stage('Checking') {
steps {
script {
println agentLabel
println agentName
}
}
}
stage('Final') {
steps {
node( agentLabel as String ) {
echo "TEST"
}
script {
println agentLabel
println agentName
}
}
}
}
}
您可以从此控制台输出中看到,它现在正确地找到了Linux节点并完成了管道。在agentName == Windows的情况下不会发生早期评估:
Started by user Admin
[Pipeline] stage
[Pipeline] { (Prep)
[Pipeline] script
[Pipeline] {
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Checking)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
Right Now the Agent Name is Linux
[Pipeline] echo
Linux
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Final)
[Pipeline] echo
Right Now the Agent Name is Linux
[Pipeline] node
Running on Slave 1 in /home/jenkinsslave/jenkins/workspace/test
[Pipeline] {
[Pipeline] echo
TEST
[Pipeline] }
[Pipeline] // node
[Pipeline] script
[Pipeline] {
[Pipeline] echo
Right Now the Agent Name is Linux
[Pipeline] echo
Linux
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] End of Pipeline
Finished: SUCCESS
没有使用懒惰的GString
和类型转换,这可能也可以工作,但我没有尝试过。