如何在Jenkins流水线中仅失败指定Stage而非整个Build?
实现仅指定Stage失败而不终止整个Jenkins流水线
要实现当cntKO > 0时仅标记「Run the Create users based on Env. defined」Stage为失败,同时让后续Stage继续执行、整个Build不失败,你需要替换直接修改currentBuild.result的方式,改用Jenkins Pipeline的catchError步骤控制错误范围,具体修改如下:
修改后的流水线代码
stages { stage('Run the Create users based on Env. defined') { options { timestamps () timeout(time: 6, unit: 'HOURS') } steps { // 用catchError控制错误影响范围:Stage标记为失败,全局Build结果保持成功 catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') { bat 'python batch\\CloudValidation\\Cloudusercreation-csvfile.py %release%' bat "batch\\CloudValidation\\usercreationoncloudnew.bat %ws% %release% %username% %pwd% %tenant% %POD%" script{ def pipeline_log1 = currentBuild.rawBuild.getLog(10000); def result1 = pipeline_log1.find { it.contains('Total Number of KO Users') } if (result1) { User_KO = result1.split("Total Number of KO Users:") cntko = User_KO[1].toInteger() if (cntko > 0) { echo "Build failed due to ${result1}" // 抛出错误触发Stage失败,由catchError处理后续状态 error("Stage failed because KO users count is ${cntko}") } } } } } } stage('xyz') { options { timestamps () timeout(time: 6, unit: 'HOURS') } steps { bat "batch\\CloudValidation\\CreatePvtCollabSpace.bat" } } }
关键修改说明
- 替换
currentBuild.result为error():直接设置currentBuild.result会修改整个Build的全局状态,改用error()抛出异常,仅触发当前Stage的失败逻辑。 - 用
catchError包裹Stage步骤:stageResult: 'FAILURE':标记当前Stage为失败状态,在Jenkins界面中该Stage会显示红色失败标识。buildResult: 'SUCCESS':保持整个Build的全局状态为成功,后续Stage会正常执行。若希望Build标记为「不稳定(UNSTABLE)」而非成功,可将此参数改为buildResult: 'UNSTABLE'。
- 兼容性注意:确保你的Jenkins版本(2.220+)或Pipeline Basic Steps插件版本足够新,以支持
catchError的参数配置。
内容的提问来源于stack exchange,提问作者Kamal Baldawa
相关产品推荐
相关产品推荐

