声明式Jenkins管道的主动选择参数

时间:2020-07-23 15:28:27

标签: jenkins jenkins-pipeline jenkins-declarative-pipeline


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

这是我的简单脚本:


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}"
            }
        }
    }
}

但是实际上第二个参数为空

enter image description here

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

UPD 有什么办法可以将列表变量传递到脚本中吗?例如

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

2 个答案:

答案 0 :(得分:3)

您需要使用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}"
            }
        }
    }
}

答案 1 :(得分:0)

从 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()
      }
   }
   ...
}