Eri*_*ire 14 groovy jenkins jenkins-pipeline
这是我的内容Jenkinsfile
:
node {
// prints only the first element 'a'
[ 'a', 'b', 'c' ].each {
echo it
}
}
Run Code Online (Sandbox Code Playgroud)
在Jenkins中执行作业时(使用Pipeline插件),仅打印列表中的第一个项目.
有人能解释我这种奇怪的行为吗?这是一个错误吗?或者只是我不理解Groovy语法?
编辑:for (i in items)
按预期工作:
node {
// prints 'a', 'b' and 'c'
for (i in [ 'a', 'b', 'c' ]) {
echo i
}
}
Run Code Online (Sandbox Code Playgroud)
mvr*_*mvr 20
这里接受的答案表明这是一个已知的错误,并使用了一个对我不起作用的解决方法,因此我将提供最近我发现的更新.
尽管JENKINS-26481的解决方案(最近,在撰写本文时)很多人可能会遇到旧版本的Jenkins,但修复程序不可用.文字列表上的for循环迭代有时可能有效,但JENKINS-46749和JENKINS-46747等相关问题似乎仍然困扰着许多用户.此外,根据Jenkinsfile中的确切上下文,可能echo
会工作而sh
失败,并且可能会无提示地失败,或者它们可能会因序列化失败而导致构建崩溃.
如果你不喜欢惊喜(跳过循环和静默失败),如果你希望你的Jenkinsfiles在Jenkins的多个版本中是最便携的,那么主要的想法似乎是你应该总是在你的for循环中使用经典计数器而忽略其他groovy特征.
这个要点是我见过的最好的参考,并列出了许多你认为应该工作相同但行为异常不同的案例.无论您正在尝试使用何种迭代,无论您是尝试使用@NonCPS
,直接在内部进行迭代node{}
,还是调用单独的函数,这都是建立健全性检查和调试设置的良好起点.
同样,我不赞成这项工作本身,但我将下面的迭代测试用例的要点嵌入后代:
abcs = ['a', 'b', 'c']
node('master') {
stage('Test 1: loop of echo statements') {
echo_all(abcs)
}
stage('Test 2: loop of sh commands') {
loop_of_sh(abcs)
}
stage('Test 3: loop with preceding SH') {
loop_with_preceding_sh(abcs)
}
stage('Test 4: traditional for loop') {
traditional_int_for_loop(abcs)
}
}
@NonCPS // has to be NonCPS or the build breaks on the call to .each
def echo_all(list) {
list.each { item ->
echo "Hello ${item}"
}
}
// outputs all items as expected
@NonCPS
def loop_of_sh(list) {
list.each { item ->
sh "echo Hello ${item}"
}
}
// outputs only the first item
@NonCPS
def loop_with_preceding_sh(list) {
sh "echo Going to echo a list"
list.each { item ->
sh "echo Hello ${item}"
}
}
// outputs only the "Going to echo a list" bit
//No NonCPS required
def traditional_int_for_loop(list) {
sh "echo Going to echo a list"
for (int i = 0; i < list.size(); i++) {
sh "echo Hello ${list[i]}"
}
}
// echoes everything as expected
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
43735 次 |
最近记录: |