如果某些步骤失败,Jenkins 管道将阶段标记为不稳定
Jenkins pipeline mark stage as unstable if some steps fail
我目前面临的问题是我想设置一个阶段,在本例中为第 2 阶段,如果某些步骤失败则设置为 "UNSTABLE",如果更多则设置为 "FAILED",例如60% 的步骤都失败了。
我的 Jenkins 文件目前看起来像这样:
pipeline {
agent any
stages {
stage("stage1") {
steps {
echo "prepare some stuff"
}
}
stage("stage2") {
steps {
parallel(
"step1": {
sh 'false'
},
"step2": {
sh 'true'
},
"step3": {
sh 'false'
}
)
}
}
stage('stage3') {
steps {
echo "do some other stuff"
}
}
}
}
尝试捕捉
如果您希望第二步运行时不考虑第一步发生的情况,您必须捕获第一步中的任何错误。您可以使用 try catch 块来做到这一点。
根据这个答案:,在声明性管道中你不能直接使用 try。您必须在脚本步骤
中包装任意 groovy 代码
stage('Maven Install') {
steps {
script {
echo "Step 1"
try {
sh "mvn clean install"
} catch (Exception err) {
//increment error count
} finally {
//do something
}
}
script {
echo "Step 2"
try {
sh "mvn clean install"
} catch (Exception err) {
//increment error count
} finally {
//do something
}
}
}
}
将阶段标记为 UNSTABLE/FAILURE
根据官方文档https://jenkins.io/doc/pipeline/tour/post/,您可以使用 always 块:
always {
echo 'One way or another, I have finished'
//put here your final logic
}
此块将在所有先前阶段都完成后执行,因此您可以在此处使用错误计数应用一些逻辑并将状态设置为整个构建:
- currentBuild.result = 'SUCCESS'
- currentBuild.result = 'FAILURE'
- 等等
我目前面临的问题是我想设置一个阶段,在本例中为第 2 阶段,如果某些步骤失败则设置为 "UNSTABLE",如果更多则设置为 "FAILED",例如60% 的步骤都失败了。
我的 Jenkins 文件目前看起来像这样:
pipeline {
agent any
stages {
stage("stage1") {
steps {
echo "prepare some stuff"
}
}
stage("stage2") {
steps {
parallel(
"step1": {
sh 'false'
},
"step2": {
sh 'true'
},
"step3": {
sh 'false'
}
)
}
}
stage('stage3') {
steps {
echo "do some other stuff"
}
}
}
}
尝试捕捉
如果您希望第二步运行时不考虑第一步发生的情况,您必须捕获第一步中的任何错误。您可以使用 try catch 块来做到这一点。
根据这个答案:
stage('Maven Install') {
steps {
script {
echo "Step 1"
try {
sh "mvn clean install"
} catch (Exception err) {
//increment error count
} finally {
//do something
}
}
script {
echo "Step 2"
try {
sh "mvn clean install"
} catch (Exception err) {
//increment error count
} finally {
//do something
}
}
}
}
将阶段标记为 UNSTABLE/FAILURE
根据官方文档https://jenkins.io/doc/pipeline/tour/post/,您可以使用 always 块:
always {
echo 'One way or another, I have finished'
//put here your final logic
}
此块将在所有先前阶段都完成后执行,因此您可以在此处使用错误计数应用一些逻辑并将状态设置为整个构建:
- currentBuild.result = 'SUCCESS'
- currentBuild.result = 'FAILURE'
- 等等