首页 > 解决方案 > 从属性中的 GroovyScript 内部访问 jenkins env 参数

问题描述

我有一份詹金斯的工作:

properties([
    parameters([
        [$class: 'ChoiceParameter', choiceType: 'PT_CHECKBOX', description: '''The name of the image to be used.''', filterLength: 1, filterable: true, name: 'OS', randomName: 'choice-parameter-15413073438404172', script: [$class: 'GroovyScript', fallbackScript: [classpath: [], sandbox: true, script: ''], script: [classpath: [], sandbox: true, script: '''templates = [
        "BB-Win7-x32-SP1",
        "BB-Win7-x64-SP1",
        "BB-Win10-x64-RS1",
        "BB-Win10-x64-RS2",
        "BB-Win10-x32-RS5"]

        return templates''']]]])
])
....
....

它正在工作并按预期为 GUI 生成复选框属性。

现在,我想根据工作空间中的文件动态生成这些选项。为此,我需要workspacegroovy 脚本中的环境变量。我怎样才能做到这一点?

标签: jenkinsjenkins-pipelinejenkins-groovy

解决方案


Jenkins 在运行管道之前需要弄清楚所有参数。因此,您的问题基本上归结为“如何在运行管道之前运行(任意)groovy 脚本?”

有两种选择:

  1. 正如我所提到的,ActiveChoice 插件允许您定义一个返回脚本的参数。然后 Jenkins 将运行脚本(不要忘记批准它),以向您显示“使用参数构建”页面。调试这个是出了名的困难,但这可能会很费劲。

  2. 或者,您可能希望在运行声明式(主要)管道之前运行脚本管道,如this answer中所述。这可能看起来有点像这样:

def my_choices_list = []

node('master') {
   stage('prepare choices') {
       // read the file contents
       def my_choices = sh script: "cat ${WORKSPACE}/file.txt", returnStdout:true
       // make a list out of it - I haven't tested this!
       my_choices_list = my_choices.trim().split("\n")
   }
}

pipeline {
   parameters { 
        choiceParam('OPTION', my_choices_list)

推荐阅读