具有声明性 Jenkins 管道的主动选择参数

Active choice parameter with declarative Jenkins pipeline


我正在尝试将主动选择参数与声明性 Jenkins 管道脚本一起使用。

这是我的简单脚本:


environments = 'lab\nstage\npro'

properties([
    parameters([
        [$class: 'ChoiceParameter',
            choiceType: 'PT_SINGLE_SELECT',
            description: 'Select a choice',
            filterLength: 1,
            filterable: true,
            name: 'choice1',
            randomName: 'choice-parameter-7601235200970',
            script: [$class: 'GroovyScript',
                fallbackScript: [classpath: [], sandbox: false, script: 'return ["ERROR"]'],
                script: [classpath: [], sandbox: false, 
                    script: """
                        if params.ENVIRONMENT == 'lab'
                            return['aaa','bbb']
                        else
                            return ['ccc', 'ddd']
                    """
                ]]]
    ])
])

pipeline {
    agent any
    tools {
        maven 'Maven 3.6'
    }
    options {
        disableConcurrentBuilds()
        timestamps()
        timeout(time: 30, unit: 'MINUTES')
        ansiColor('xterm')
    }
    parameters {
        choice(name: 'ENVIRONMENT', choices: "${environments}")
    }
    stages {
        stage("Run Tests") {
            steps {
                sh "echo SUCCESS on ${params.ENVIRONMENT}"
            }
        }
    }
}

但实际上第二个参数为空

是否可以同时使用脚本化主动选择参数和声明参数?

UPD 有没有办法将列表变量传递给脚本?例如

List<String> someList = ['ttt', 'yyyy']
...
script: [
    classpath: [], 
    sandbox: true, 
    script: """
        if (ENVIRONMENT == 'lab') { 
            return someList
        }
        else {
            return['ccc', 'ddd']
        }
    """.stripIndent()
]

您需要使用 Active Choices Reactive Parameter 使当前作业参数引用另一个作业参数值

environments = 'lab\nstage\npro'

properties([
    parameters([
        [$class: 'CascadeChoiceParameter', 
            choiceType: 'PT_SINGLE_SELECT',
            description: 'Select a choice',
            filterLength: 1,
            filterable: true,
            name: 'choice1',
            referencedParameters: 'ENVIRONMENT',
            script: [$class: 'GroovyScript',
                fallbackScript: [
                    classpath: [], 
                    sandbox: true, 
                    script: 'return ["ERROR"]'
                ],
                script: [
                    classpath: [], 
                    sandbox: true, 
                    script: """
                        if (ENVIRONMENT == 'lab') { 
                            return['aaa','bbb']
                        }
                        else {
                            return['ccc', 'ddd']
                        }
                    """.stripIndent()
                ]
            ]
        ]
    ])
])

pipeline {
    agent any

    options {
        disableConcurrentBuilds()
        timestamps()
        timeout(time: 30, unit: 'MINUTES')
        ansiColor('xterm')
    }
    parameters {
        choice(name: 'ENVIRONMENT', choices: "${environments}")
    }
    stages {
        stage("Run Tests") {
            steps {
                sh "echo SUCCESS on ${params.ENVIRONMENT}"
            }
        }
    }
}

从 Jenkins 2.249.2 开始,没有任何插件并使用声明式管道, 以下模式使用动态下拉菜单提示用户(供他选择分支):

(周围的 withCredentials 块是可选的,仅当您的脚本和 jenkins configuratoin 确实使用凭据时才需要)

节点{

withCredentials([[$class: 'UsernamePasswordMultiBinding',
              credentialsId: 'user-credential-in-gitlab',
              usernameVariable: 'GIT_USERNAME',
              passwordVariable: 'GITLAB_ACCESS_TOKEN']]) {
    BRANCH_NAMES = sh (script: 'git ls-remote -h https://${GIT_USERNAME}:${GITLAB_ACCESS_TOKEN}@dns.name/gitlab/PROJS/PROJ.git | sed \'s/\(.*\)\/\(.*\)/\2/\' ', returnStdout:true).trim()
}

} 管道 {

agent any

parameters {
    choice(
        name: 'BranchName',
        choices: "${BRANCH_NAMES}",
        description: 'to refresh the list, go to configure, disable "this build has parameters", launch build (without parameters)to reload the list and stop it, then launch it again (with parameters)'
    )
}

stages {
    stage("Run Tests") {
        steps {
            sh "echo SUCCESS on ${BranchName}"
        }
    }
}

}

缺点是应该刷新 jenkins 配置并使用空白 运行 来使用脚本刷新列表 ...

解决方案(不是我提出的):使用用于专门刷新值的附加参数可以减少此限制:

parameters {
        booleanParam(name: 'REFRESH_BRANCHES', defaultValue: false, description: 'refresh BRANCH_NAMES branch list and launch no step')
}

然后在舞台上:

stage('a stage') {
   when {
      expression { 
         return ! params.REFRESH_BRANCHES.toBoolean()
      }
   }
   ...
}