You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Groovy脚本化Jenkins函数中为DynamicReferenceParameter传递全局变量

解决方案

问题核心在于动态参数的Groovy脚本是独立执行环境,和流水线主脚本不在同一个上下文,直接引用全局变量或函数参数都会失效。要实现全局复用partitions,需要把全局变量的内容嵌入到动态脚本字符串中,让动态脚本能解析复用。

具体实现步骤:

  1. 在流水线最顶部定义全局分区映射,方便所有函数访问
  2. 修改getImageParameter,直接复用全局映射的Key生成镜像选项,避免重复维护
  3. 修改getPartitionParameter,将全局分区映射序列化为可解析的字符串,嵌入到动态参数的脚本中

修改后的完整代码:

// 全局定义分区映射,可在多个函数中复用
def globalPartitions = [
    'market': ['app'],
    'collection': ['app', 'web']
]

def parametersList = [
    choice(name: 'DO_BUILD', choices: ["----","true"].join("\n"), description: 'Confirm to build image'),
]

parametersList.add(getImageParameter())
parametersList.add(getPartitionParameter())

properties([parameters(parametersList)])

stage('Create AMI'){
  // stage code goes here
}

def getImageParameter() {
    return [
        $class: 'ChoiceParameter', 
        choiceType: 'PT_SINGLE_SELECT', 
        description: 'Select an image to build:',
        name: 'image',
        script: [
            $class: 'GroovyScript', 
            script: [
                classpath: [],
                sandbox: false,
                // 直接复用全局映射的Key,避免硬编码
                script: "return " + globalPartitions.keySet().inspect()
            ]
        ]
    ]
}

def getPartitionParameter() {
    // 将全局分区映射序列化为Groovy可解析的字符串
    def serializedPartitions = globalPartitions.inspect()
    
    return [
        $class: 'DynamicReferenceParameter', 
        choiceType: 'ET_FORMATTED_HTML', 
        name: 'partition',
        referencedParameters: 'image',
        script: [
            $class: 'GroovyScript', 
            script: [
                classpath: [],
                sandbox: false,
                script: '''
                    // 解析嵌入的全局分区映射
                    def partitions = ''' + serializedPartitions + '''
                    
                    def html = "Select a partition for image <b>${image}</b> :<br>"
                    html += "<select name='partition'>"
                    
                    partitions[image]?.each { partition ->
                        html += "<option value='${partition}'>${partition}</option>"
                    }
                    
                    html += "</select>"
                    return html
                '''
            ]
        ]
    ]
}

关键说明:

  • 使用inspect()方法将全局映射转换成Groovy字面量字符串,这样动态脚本可以直接解析为原映射对象
  • getImageParameter通过复用globalPartitions.keySet()生成镜像选项,后续新增镜像只需修改全局映射,无需修改参数逻辑
  • 动态参数脚本本质是字符串拼接,我们把全局变量的内容直接写入脚本字符串,让独立执行环境能获取到数据

内容的提问来源于stack exchange,提问作者Rafiq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 12:47:14