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

如何在Jenkins Pipeline Groovy脚本中解析Curl返回的JSON并触发依赖任务

Jenkins Pipeline修复:解析JSON依赖数组并触发对应任务

原代码问题分析

  • 拼写错误:stage名称里的Dependecies、文件名sample.jason应为Dependencies和sample.json,可能导致URL请求或后续解析异常
  • 多余操作:response.join(" ")完全没必要——sh returnStdout:true已经返回完整的字符串响应,这步拼接会直接导致JSON解析失败
  • 核心逻辑缺失:没有遍历依赖数组、触发对应Jenkins任务的代码

修复后的完整Pipeline脚本

pipeline {
    agent {
        label 'Dep-Demo'
    }
    stages {
        stage('获取依赖JSON对象') {
            steps {
                script {
                    final String url = "https://***************/repository/files/sample.json/raw?ref=main"
                    withCredentials([usernamePassword(credentialsId: 'api', passwordVariable: 'PASSWORD', usernameVariable: 'USELESS')]) {
                        // 获取并清理JSON响应
                        def response = sh(script: "curl -s --header \"PRIVATE-TOKEN: \$PASSWORD\" $url", returnStdout: true).trim()
                        echo "获取到的响应内容: $response"
                        
                        // 解析JSON数据
                        def jsonObj = readJSON text: response
                        echo "解析后的JSON对象: ${jsonObj}"
                        
                        // 遍历依赖数组,触发对应Jenkins任务
                        if (jsonObj.Dependencies && jsonObj.Dependencies instanceof List) {
                            jsonObj.Dependencies.each { depName ->
                                echo "开始触发任务: ${depName}"
                                // 触发任务,wait:false表示异步执行,可根据需求改为true同步等待
                                build job: depName, wait: false
                            }
                        } else {
                            error "未找到有效的Dependencies数组"
                        }
                    }
                }
            }
        }
    }
    post {
        failure {
            echo "Pipeline执行失败,请检查URL、凭证或任务配置"
        }
    }
}

关键修复说明

  1. 修正拼写错误:把所有jason改为json、Dependecies改为Dependencies,避免低级错误
  2. 优化curl请求:给$PASSWORD加转义符\防止Jenkins提前解析变量;用.trim()清理响应前后空白,避免JSON解析报错
  3. 正确解析JSON:直接用readJSON text: response解析,去掉多余的join操作
  4. 添加任务触发逻辑:先判断Dependencies数组是否有效,再遍历每个依赖项,用build步骤触发对应Jenkins任务,同步/异步可通过wait参数调整
  5. 增加错误提示:post阶段的failure块和数组校验逻辑,方便排查问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 20:15:32