如何在Jenkins中基于shell返回JSON实现循环控制流水线执行状态
需求实现方案
这个需求完全可以实现,你只需要在script块中添加循环轮询逻辑、JSON解析能力和分支判断即可,具体实现步骤如下:
前置依赖
你可以二选一选择实现方式,对应前置要求如下:
- 方式一(Jenkins原生插件实现):提前在Jenkins插件管理中安装 Pipeline Utility Steps 插件,该插件提供的
readJSON方法可以直接解析shell脚本返回的JSON数据,无需手动处理字符串 - 方式二(系统工具实现):确保Jenkins运行的agent节点已安装jq工具,直接通过shell命令解析JSON,无需额外安装Jenkins插件
方式一完整流水线代码
pipeline { agent any stages { stage('TestStage') { steps { script { def status = "running" // 轮询检测状态 while (status == "running") { // 执行脚本并捕获返回的JSON内容,trim去掉首尾换行空格 def scriptOutput = sh(script: "testfile.sh", returnStdout: true).trim() // 解析JSON获取Status字段值 def jsonData = readJSON text: scriptOutput status = jsonData.Worker[0].Status // 状态判断 if (status == "failure") { // 状态为失败直接终止流水线,抛出错误信息 error "检测到任务执行失败,流水线终止" } else if (status == "running") { // 状态仍为运行中,休眠10秒后再次检测,可根据需要调整休眠时长 sleep 10 } } // 执行到此处说明status为success,自动跳出循环继续执行后续步骤 } } } // 后续的其他stage可以正常写在这里 stage('后续步骤') { steps { echo "任务执行成功,继续执行后续流程" } } } }
方式二(jq工具实现)script块替换代码
如果选用jq工具实现,仅需把TestStage中的script块内容替换为以下代码即可:
script { def status = "running" while (status == "running") { status = sh(script: "testfile.sh | jq -r '.Worker[0].Status'", returnStdout: true).trim() if (status == "failure") { error "检测到任务执行失败,流水线终止" } else if (status == "running") { sleep 10 } } }
核心逻辑说明
- 初始化状态为running,进入循环后每次调用testfile.sh获取最新状态
- 检测到状态为failure时直接调用
error方法终止流水线,构建结果标记为失败 - 检测到状态为running时休眠指定时长后再次循环检测,避免频繁调用脚本占用资源
- 检测到状态为success时自动跳出循环,继续执行流水线后续的所有步骤
内容的提问来源于stack exchange,提问作者Alfred
相关产品推荐
相关产品推荐

