用于检查生成步骤 = 失败的声明性管道,然后触发下一个生成步骤,但不会使作业失败



我正在尝试使 Jenkinsfile 中的构建步骤失败,失败的结果 = 失败。一旦步骤失败,它将触发我的回滚作业。 尝试了很多不同的东西,但没有运气。任何帮助将不胜感激。

pipeline {
agent any
stages {
stage('Git Checkout') {
steps {
script {
git 'somegit-repo'
sh'''
mvn package
'''
echo currentBuild.result
catchError {
build 'rollback'
}
}
}
} 
}

一种方法是使用 shell 脚本和exit 1语句 例如

sh "exit 1"

或者您可以使用错误步骤

error('Failing build because...')

见 https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/#error-error-signal

使用trycatch

node {
stage("Run scripts") {
try {
<some command/script> 
} catch (error) {
<rollback command/script>
}
}
}

非常感谢。这似乎有效!

stages {
stage("some test") {
steps{ 
script {
git 'mygitrepo.git'
try {
sh''' mvn test '''
} catch (error) {
script {
def job = build job: 'rollback-job'
}
}
}
}
}

如果您查看清洁和通知页面

您可以执行post步骤,摆脱所有尝试/捕获的内容并获得更干净的 Jenkinsfile

pipeline {
agent any
stages {
stage('No-op') {
steps {
sh 'ls'
}
}
}
post {
always {
echo 'One way or another, I have finished'
deleteDir() /* clean up our workspace */
}
success {
echo 'I succeeeded!'
}
unstable {
echo 'I am unstable :/'
}
failure {
echo 'I failed :('
}
changed {
echo 'Things were different before...'
}
}
}

最新更新