您可以将逻辑编写在 Groovy 文件中,您可以将其保存在 Git 存储库中,或者保存在管道共享库 https://jenkins.io/doc/book/pipeline/shared-libraries/,或其他地方。
例如,如果您有文件utils.groovy
在你的存储库中:
List<Integer> myNumbers() {
return [1, 2, 3, 4, 5]
}
return this
In your Jenkinsfile
,你可以通过这样使用它load step https://jenkins.io/doc/pipeline/steps/workflow-cps/#code-load-code-evaluate-a-groovy-source-file-into-the-pipeline-script:
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`…
}