Jenkins Groovy如何从@NonCPS方法调用方法而不结束管道 [英] Jenkins Groovy how to call methods from @NonCPS method without ending pipeline
问题描述
我需要在Jenkins Pipeline中解析一些JSON,并在循环中调用一些常规方法,但脚本始终在第一次函数调用后退出。如何做到这一点?
import groovy.json.JsonSlurper
import com.cloudbees.groovy.cps.NonCPS
@NonCPS
def myMethod(String json){
def jsonSlurper = new JsonSlurper()
def jsonObject = jsonSlurper(json)
jsonObject.each {
obj - >
switch(obj.name){
casefoo:
doAThing(obj)
break
casebar:
doAnotherThing(obj)
break
}
}
}
上面的例子中,即使有一个json对象,如下所示:
[{
name:foo
$ b $ name
$ p
$ > ...管道总是在第一次迭代后退出。这大概是由于混合同步和异步功能。有没有办法做到这一点?解决方案我已经通过执行以下操作来解决此问题:
import groovy.json.JsonSlurper
$ b $ def myMethod(String json){
def jsonSlurper = new JsonSlurper )
def jsonObject = jsonSlurper(json)
jsonSlurper = null
for(int i = 0; i< jsonObject.size(); i ++){
switch(jsonObject [ i] .name){
casefoo:
doAThing(jsonObject [i])
break
casebar:
doAnotherThing(jsonObject [i] )
break
}
}
}
使用后立即销毁JsonSlurper实例,删除@NonCPS注释,切换到c样式for循环而不是每个循环。
I need to parse some JSON in a Jenkins Pipeline and call some regular methods in a loop, however the script always exits after the first function call. How to do this?
import groovy.json.JsonSlurper
import com.cloudbees.groovy.cps.NonCPS
@NonCPS
def myMethod(String json) {
def jsonSlurper = new JsonSlurper()
def jsonObject = jsonSlurper(json)
jsonObject.each {
obj ->
switch(obj.name) {
case "foo":
doAThing(obj)
break
case "bar":
doAnotherThing(obj)
break
}
}
}
In the above example, even with a json object like:
[{
"name": "foo"
}, {
"name": "bar"
}]
...the pipeline always exits after the first iteration. This is presumably due to mixing sync and async functions. Is there any way to do this?
解决方案 I've resolved this issue essentially by doing the following:
import groovy.json.JsonSlurper
def myMethod(String json) {
def jsonSlurper = new JsonSlurper()
def jsonObject = jsonSlurper(json)
jsonSlurper = null
for(int i = 0; i < jsonObject.size(); i++) {
switch(jsonObject[i].name) {
case "foo":
doAThing(jsonObject[i])
break
case "bar":
doAnotherThing(jsonObject[i])
break
}
}
}
Immediately destroy the JsonSlurper instance after it's used, remove @NonCPS annotation, switch to a c-style for loop instead of each.
这篇关于Jenkins Groovy如何从@NonCPS方法调用方法而不结束管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!