Conditional within Jenkins `tool` block?

We use Jenkins shared libraries and need to support the ability of individual repositories to override the default JDK. We have added OpenJDK-20 and OpenJDK-11 in Jenkins > Manage Jenkins as available JDKs alongside the default JDK 8. Now, how can I express this conditional within the tools block?

Current pipeline definition (debug_pipeline.groovy):

// Jenkins declarative pipeline for debugging Jenkins agent

def call (body) {
    def pipelineParams= [:]
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body.delegate = pipelineParams

    pipeline {
        agent any
        options {
            // Prepend all console output generated by the
            // Pipeline run with the time at which the line was emitted
        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 {
            stage('Debug') {
                steps {
                    sh 'command -v java && java -version'
                    sh 'command -v mvn && mvn -version'

Now, I would like for the use of JDK 11 or 20 to be optional by having projects use pipeline parameters to specify them. I have tried:

        tools {
            if (pipelineParams.maven != 'system') {
                maven pipelineParams.maven
            if (pipelineParams.jdk != 'system') {
                jdk pipelineParams.jdk

And the invoking repository’s Jenkinsfile:

@Library('pipeline-library') _

debug_pipeline {
    Greeting = 'Goodbye'
    jdk = 'OpenJDK-20'
    maven = 'apache-maven-3.9.3'

However, this errors with debug_pipeline.groovy: 15: Expected to find ‘someTool "someVersion"’. It also seems that I cannot use when within tools.

So, how can I effectively allow projects to override the JDK using pipeline parameters?

Jenkins setup: Jenkins 2.346.3 with Linux agents.

(reposted from groovy - Conditional within Jenkins `tool` block - Stack Overflow)

Hi @brsolomon-deloitte and welcome to this community :wave:

As far as I know, in Jenkins declarative pipelines, the tools block does not support conditional statements like if or when.

However, you could maybe achieve the ability to override the JDK and Maven versions using pipeline parameters in a slightly different way.

Instead of directly specifying the tools in the tools block, I think you could use the environment block to set the JAVA_HOME and PATH environment variables based on the pipeline parameters.