enkins中的Pipeline插件在Jenkinsfile中调

enkins中的Pipeline插件在Jenkinsfile中调

本文介绍了如何使用Jenkins中的Pipeline插件在Jenkinsfile中调用Java函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在jenkins中使用管道插件.我的JenkinsfilenumToEcho =1,2,3,4,但是我想调用Test.myNumbers()以获得值列表.

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.

  1. 如何在Jenkinsfile中调用myNumbers()java函数?
  2. 还是我需要一个单独的Groovy脚本文件,并将该文件放置在具有Test类的java jar中?

我的Jenkins文件:

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);
 }
}

推荐答案

您可以在Groovy文件中编写逻辑,该文件可以保存在Git存储库中,也可以保存在管道共享库或其他地方.

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.

例如,如果您的存储库中有文件utils.groovy:

For example, if you had the file utils.groovy in your repository:

List<Integer> myNumbers() {
  return [1, 2, 3, 4, 5]
}
return this

在您的Jenkinsfile中,您可以通过 load步骤:

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`…


或者,您可以签出Java代码并运行它,并捕获输出.然后,您可以将其解析为列表,或稍后在管道中所需的任何数据结构.例如:


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`…
}

这篇关于如何使用Jenkins中的Pipeline插件在Jenkinsfile中调用Java函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 06:36