I am using pipeline plugin in jenkins. My Jenkinsfile
has numToEcho =1,2,3,4
but I want to call Test.myNumbers()
to get list of values.
- How can I call myNumbers() java function in Jenkinsfile?
- Or do I need to have a separate groovy script file and that file I should place inside java jar which has Test class?
My Jenkinsfile:
def numToEcho = [1,2,3,4] def stepsForParallel = [:] for (int i = 0; i < numToEcho.size(); i++) { def s = numToEcho.get(i) def stepName = "echoing ${s}" stepsForParallel[stepName] = transformIntoStep(s) } parallel stepsForParallel def transformIntoStep(inputNum) { return { node { echo inputNum } } } import com.sample.pipeline.jenkins public class Test{ public ArrayList<Integer> myNumbers() { ArrayList<Integer> numbers = new ArrayList<Integer>(); numbers.add(5); numbers.add(11); numbers.add(3); return(numbers); } }
You could write your logic in a Groovy file, which you can keep in a Git repository, or in a Pipeline Shared Library, or elsewhere.
For example, if you had the file utils.groovy
in your repository:
List<Integer> myNumbers() { return [1, 2, 3, 4, 5] } return this
In your Jenkinsfile
, you could use it like this via the load
step:
def utils node { // Check out repository with utils.groovy git 'https://github.com/…/my-repo.git' // Load definitions from repo utils = load 'utils.groovy' } // Execute utility method def numbers = utils.myNumbers() // Do stuff with `numbers`…
Alternatively, you can check out your Java code and run it, and capture the output. Then you could parse that into a list, or whatever data structure you need for later in the pipeline. For example:
node { // Check out and build the Java tool git 'https://github.com/…/some-java-tools.git' sh './gradlew assemble' // Run the compiled Java tool def output = sh script: 'java -jar build/output/my-tool.jar', returnStdout: true // Do some parsing in Groovy to turn the output into a list def numbers = parseOutput(output) // Do stuff with `numbers`… }