Jenkins Groovy how to call methods from @NonCPS method without pipeline

I need to parse 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 it?

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, for example:

 [{ "name": "foo" }, { "name": "bar" }] 

... the pipeline always exits after the first iteration. This is probably due to synchronization and asynchronous functions. Is there any way to do this?

+5
source share
2 answers

I solved this problem by following these steps:

 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 using it, delete the @NonCPS annotation, switch to the c loop cycle, not each.

+7
source

To clarify, this is described as an unsupported function - https://github.com/jenkinsci/workflow-cps-plugin/#technical-design

You cannot call regular (CPS-converted) Pipeline methods or steps from the @NonCPS method, so it is best to use them to perform some calculations before passing the resume back to the main script.

+2
source

Source: https://habr.com/ru/post/1247161/


All Articles