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

Jenkins Groovy遍历JSON无法获取imageFamily值及触发构建求助

解决Jenkins Groovy遍历JSON获取参数及触发构建问题

问题原因

你的循环遍历方式错误,json.instances是对象数组,每个元素包含instanceName和imageFamily属性,不能直接通过json.instances.instanceName[i]访问,应该先取数组的第i个元素,再获取对应属性。另外,你完全可以跳过JSON序列化再解析的步骤,直接用处理后的集合遍历,更简洁高效。

修正后的代码

stage("Create Instances"){
    steps {
        script {
            def instances = [ 
                [ instance_name : { 'webserver' }, image_family : { 'ubuntu' } ], 
                [ instance_name : { 'api' }, image_family : { 'redhat' } ]     
            ]

            // 直接处理成可用的集合,无需转JSON再解析
            def instanceList = instances.collect { 
                [
                    instanceName: it.instance_name(), 
                    imageFamily: it.image_family()
                ] 
            }

            // 遍历集合,打印参数并触发构建
            instanceList.each { instance ->
                println "实例名称: ${instance.instanceName}"
                println "镜像家族: ${instance.imageFamily}"

                // 触发目标Jenkins任务,传递imageFamily参数
                build job: '你的目标任务名称', 
                    parameters: [
                        [$class: 'StringParameterValue', name: 'IMAGE_FAMILY', value: instance.imageFamily],
                        // 可添加其他需要传递的参数,比如instanceName
                        [$class: 'StringParameterValue', name: 'INSTANCE_NAME', value: instance.instanceName]
                    ],
                    wait: false // 根据需求设置是否等待任务完成
            }
        }
    }
}

关键说明

  1. 遍历方式修正:使用each直接遍历处理后的instanceList集合,每个元素是包含instanceName和imageFamily的Map,直接通过键名访问即可,避免数组索引访问的错误。
  2. 简化流程:去掉了JsonOutput和JsonSlurperClassic的序列化解析步骤,因为原始集合处理后已经可以直接使用,无需额外转换。
  3. 触发构建:使用Jenkins内置的build步骤,指定任务名称和参数,其中StringParameterValue用于传递字符串类型参数,你可以根据实际参数类型调整(比如布尔型用BooleanParameterValue)。wait: false表示不等待构建完成,若需要等待任务结束再继续流水线,可改为wait: true。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 17:02:43