Jenkins流水线超时后仍标记成功,如何终止任务并发送告警?
解决方案
方案1:超时后直接中止整个流水线
默认timeout步骤仅中断当前执行,但不会将阶段标记为失败,导致流水线继续推进后续阶段。可以通过catchError强制将超时或执行错误的状态转为FAILURE,让流水线直接中止:
stages { stage('Stage1') { options { timeout(time: 1, unit: "MINUTES") } steps { script { // 捕获超时或脚本执行错误,将阶段和构建结果设为FAILURE catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') { sh ''' #!/bin/bash set -eux pipefail ssh user@server.com " ssh -p 50 user@localhost ' docker run --rm --name name\ -e user=...\ -e passwd=...\ -v /location:/location2\ -w location2\ server2.com:6000/my-x-y:1.1\ python script.py ' " ''' } } } } }
当脚本执行超时或失败时,Stage1会直接标记为失败,整个流水线终止,不会进入下一阶段。
方案2:异常/超时后发送通知(可选择是否中止流水线)
如果需要在阶段执行异常(包括超时、脚本执行失败)时调用notification.sh发送通知,可以利用Jenkins的post阶段,在阶段结束后根据状态触发操作:
stages { stage('Stage1') { options { timeout(time: 1, unit: "MINUTES") } steps { script { // 捕获超时/错误,仅标记阶段失败(若要中止流水线,需添加buildResult: 'FAILURE') catchError(stageResult: 'FAILURE') { sh ''' #!/bin/bash set -eux pipefail ssh user@server.com " ssh -p 50 user@localhost ' docker run --rm --name name\ -e user=...\ -e passwd=...\ -v /location:/location2\ -w location2\ server2.com:6000/my-x-y:1.1\ python script.py ' " ''' } } } post { // 脚本执行失败时触发通知 failure { sh './notification.sh' } // 超时导致阶段中断时触发通知 aborted { sh './notification.sh' } } } }
关键说明
catchError参数控制:如果不设置buildResult,仅标记当前阶段失败,流水线会继续执行后续阶段;若添加buildResult: 'FAILURE',整个流水线会直接中止。- 原shell脚本引号修正:你代码里
ssh -p 50 user@localhost'\的引号位置有误,调整为ssh -p 50 user@localhost '可避免转义异常。
内容的提问来源于stack exchange,提问作者fr0zt
相关产品推荐
相关产品推荐

