首页 > 解决方案 > 如何在 Jenkins 中创建一个脚本循环,该循环根据 shell 命令接收的 json 继续或返回成功/错误到管道?

问题描述

我在我的 Linux Box 中使用最新的 Jenkins。我正在尝试使用如下脚本块创建管道;

pipeline {
    agent any
    stages {
        stage('TestStage') { 
            steps {
                script {
                    sh "testfile.sh"
                }
            }
        }
    }
}

testfile.sh将返回如下所示的 json 文本;

{
    "Worker": [
        {
            "Status": "running"
        }
    ]
}

Status可以是runningsuccessfailure。如果是running,代码必须再次调用testfile.sh并检查状态。如果是success,管道必须继续下一步,如果是failure,管道必须终止。有可能实现这一目标吗?

谢谢。

标签: jenkinsjenkins-pipelinejenkins-groovy

解决方案


您可以通过创建一个执行脚本的while循环来实现,读取输出并检查其值直到给定的超时,当状态不再是running您可以检查结果并根据最终状态使构建失败。
就像是:

 pipeline {
     agent any
     stages {
         stage('TestStage') {
             steps {
                 script {
                     timeout(time: 1, unit: 'HOURS') {  // timeout for the 'running' period
                         def status = sh script: 'testfile.sh', returnStdout: true
                         while (status == 'running') {
                             sleep time: 10, unit: 'SECONDS'  // sleep between iterations
                             def output = sh script: 'testfile.sh', returnStdout: true
                             def dict = readJSON text: output
                             status = dict.Worker.Status
                         }
                     }
                     if(status == 'failure'){
                         error "Operation has ended with status 'failure'"
                     }
                 }
             }
         }
     }
 }

您可以找到有关相关步骤的更多信息:sleeptimeouterrorreadJSON


推荐阅读