【问题标题】:How to set a Jenkins pipeline stage to unstable based on a script exit code?如何根据脚本退出代码将 Jenkins 管道阶段设置为不稳定?
【发布时间】:2021-11-05 16:23:01
【问题描述】:

我的 Jenkins 管道中的一个阶段应设置为不稳定,具体取决于脚本在其步骤中的退出代码:2 应将阶段状态设置为不稳定,而 1 应将阶段结果设置为失败。

如何做到这一点?我检查了“catchError”,但它似乎没有区分失败状态,只提供一种捕获非 0 退出(1,2...)的方法。

pipeline {
    agent any

    parameters {
         string(name: 'FOO', defaultValue: 'foo', description: 'My foo param')
         string(name: 'BAR', defaultValue: 'bar', description: 'My bar param')
    }

    stages {
        stage('First') {
            steps {
                    // If "script.py" exit code is 2, set stage to unstable
                    // If "script.py" exit code is 1, set stage to failed 
                    
                       sh """
                          . ${WORKSPACE}/venv/bin/activate
                          python ${WORKSPACE}/script.py --foo ${FOO} --bar ${BAR}
                          deactivate
                       """
                }
            }
        }
        stage('Second') {
            steps {
                echo('Second step')
            }
        }
    }
}

【问题讨论】:

  • 我的答案已根据您的要求更新/修复

标签: python-3.x jenkins jenkins-pipeline


【解决方案1】:

解决方案

您需要执行以下步骤

  1. 将所有代码放入script 块中
  2. 修改sh返回状态码
  3. 使用条件检查状态码
  4. 使用catchError 引发并捕获错误。将 build 设置为 SUCCESS,将 stage 设置为 FAILURE 或 UNSTABLE

我使用error 强制异常,但您也可以使用sh 'exit 1'throw new Exception('')

pipeline {
    agent any

    parameters {
         string(name: 'FOO', defaultValue: 'foo', description: 'My foo param')
         string(name: 'BAR', defaultValue: 'bar', description: 'My bar param')
    }

    stages {
        stage('First') {
            steps {
                script {
                    
                    def pythonScript = """
                          . ${WORKSPACE}/venv/bin/activate
                          python ${WORKSPACE}/script.py --foo ${FOO} --bar ${BAR}
                          deactivate
                          """
                    
                    def statusCode = sh( script:pythonScript, returnStatus:true )
                    
                    
                    if(statusCode == 2) {
                        catchError(buildResult: 'SUCCESS', stageResult: 'UNSTABLE') {
                            error 'STAGE UNSTABLE'
                        }
                    } else if(statusCode == 1) {
                        catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
                            error 'STAGE FAILURE'
                        }
                    }
                            
                }
            }
        }
    }
}
    

【讨论】:

  • 感谢您的回答,但我需要将舞台结果设置为 UNSTABLE,而不是整个构建。
  • @donmelchior 如果此更新满足您的要求,请告诉我。我知道你说你尝试了catchError,但看起来你并没有把catchError 放在条件中,而且你没有得到返回码来比较
  • 这正是我需要的,谢谢
  • @donmelchior 很棒。别客气。感谢您接受答案并点赞
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多