gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:55:13 27 4
gpt4 key购买 nike

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

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

我的 Jenkins 文件:

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 存储库中,或者保存在 Pipeline Shared Library 中。 ,或其他地方。

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

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

在您的 Jenkinsfile 中,您可以通过 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 代码并运行它,然后捕获输出。然后,您可以将其解析为列表,或者稍后在管道中需要的任何数据结构。例如:

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 - 如何使用Jenkins中的Pipeline插件调用Jenkinsfile中的java函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42781864/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com