如何使用 Jenkins 中的 Pipeline 插件调用 Jenkinsfile 中的 java 函数

Use*_*345 4 plugins jenkins jenkins-pipeline

我在 jenkins 中使用管道插件。我Jenkinsfile有,numToEcho =1,2,3,4但我想打电话Test.myNumbers()来获取值列表。

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

我的詹金斯档案:

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);
 }
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*Orr 5

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

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

List<Integer> myNumbers() {
  return [1, 2, 3, 4, 5]
}
return this
Run Code Online (Sandbox Code Playgroud)

在您的 中Jenkinsfile,您可以通过以下load步骤使用它:

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`…
Run Code Online (Sandbox Code Playgroud)

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

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`…
}
Run Code Online (Sandbox Code Playgroud)

  • 好吧,你可以在 Jenkins 中运行任何东西,所以你可以运行你的 Java 程序并解析它的输出。我已经更新了答案以包含一个示例。 (2认同)