我们使用Jenkins共享库,需要支持单个存储库覆盖默认JDK的能力。我们已经在Jenkins > Manage Jenkins中添加了OpenJDK-20
和OpenJDK-11
作为可用的JDK,以及默认的JDK 8。现在,我如何在tools
块中表达这个条件?
当前管道定义(debug_pipeline.groovy
):
// Jenkins declarative pipeline for debugging Jenkins agent
def call (body) {
def pipelineParams= [:]
body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = pipelineParams
body()
pipeline {
agent any
options {
// Prepend all console output generated by the
// Pipeline run with the time at which the line was emitted
timestamps()
}
tools {
// Define tools to auto-install and put on the PATH
// The tool name must be pre-configured in Jenkins under Manage Jenkins → Tools.
maven 'apache-maven-3.9.3'
jdk 'OpenJDK-20'
}
stages {
stage('Initialize') {
steps {
hello(pipelineParams.greeting)
}
}
stage('Debug') {
steps {
sh 'command -v java && java -version'
sh 'command -v mvn && mvn -version'
}
}
}
}
}
字符串
现在,我希望JDK 11或20的使用是可选的,让项目使用管道参数来指定它们。我试过:
tools {
if (pipelineParams.maven != 'system') {
maven pipelineParams.maven
}
if (pipelineParams.jdk != 'system') {
jdk pipelineParams.jdk
}
}
型
调用仓库的Jenkinsfile
:
@Library('pipeline-library') _
debug_pipeline {
Greeting = 'Goodbye'
jdk = 'OpenJDK-20'
maven = 'apache-maven-3.9.3'
}
型
但是,这与debug_pipeline.groovy: 15: Expected to find ‘someTool "someVersion"’
错误。似乎我也不能在tools
中使用when
。
那么,我如何才能有效地允许项目使用管道参数覆盖JDK呢?
1条答案
按热度按时间inn6fuwd1#
您正确地指出,
tool {}
不允许您使工具包含具有条件(在大括号内)。修复/解决这个问题的最好方法是直接在
def pipelineParams = [:]
内部添加默认值;这些默认值将被Jenkinsfile(debug_pipeline {...}
)的输入覆盖。这样做是因为您指定了:def call (body) {}
内部的body.resolveStrategy = Closure.DELEGATE_FIRST
、body.delegate = pipelineParams
和body()
。示例如下:字符串
型
将导致:
型
考虑到您正在使用pipeline library,您甚至可以创建一个 “helper” 类(在src内部)并集中工具版本。如果您有多个管道或一个工具的多个版本,这真的很有帮助;因此,只有helper类 * 必须 * 更改,而不是所有管道和Jenkins文件。示例如下:
型
允许您使用:
型
型