Jenkins 声明式管道 - 运行多个 paralellel 的东西,但如果发生早期故障,则跳过"branch"



我想构建一个Jenkins管道,在程序的多个版本上构建和运行测试(例如,不同的数据库(但当任何一个步骤失败时,我只想跳过下面的步骤;分支";可以这么说。。

这是我的示例代码,第一阶段首先运行,可能有并行步骤(1.a,1.b(。该代码不起作用,只是我希望它如何工作的某种示例:

pipeline {
agent any
environment {
stageOneFailed = "false"
stageTwoFailed = "false"
}


stages {
stage ("Stage 1") {
parallel {
stage("Stage 1.a") {
// Something like this maybe?
steps {
catchError(buildResult: 'UNSTABLE', stageResult: 'FAILURE') {
// Do stuff here..
}
}
post {
unsuccessful {
// When stage did not succeed..
// Set stageOneFailed = "true"
}
}
}

stage("Stage 1.b") {
// Do Stuff..
// If Stage 1.b fails, set stageTwoFailed="true"
}
}
}

stage("Stage 2") {
parallel {
// Only run stages if earlier steps didn't fail
stage("Stage 2.a") {
when {
environment(name: "stageOneFailed", value: "false")
}
steps {
// Do stuff..
// If Stage 2.a fails, set stageOneFailed="true"
}
}
stage("Stage 2.b") {
when {
environment(name: "stageTwoFailed", value: "false")
}
steps {
// Do stuff..
// If Stage 2.b fails, set stageTwoFailed="true"
}
}
}
}

// stage()
}
}

有人能就如何正确地做到这一点提出建议吗?

提前感谢

EDIT:更改了代码示例。示例现在运行!

pipeline {
agent any
environment {
stageOneFailed = "false"
stageTwoFailed = "false"
}


stages {
stage ("Stage 1") {
parallel {
stage("Stage 1.a") {
steps {
catchError(buildResult: 'UNSTABLE', stageResult: 'FAILURE') {
bat "ech Stage 1.a" // Should fail because ech is no valid command
}
}
post {
failure  {
script {
env.stageOneFailed = "true"
}
}
}
}

stage("Stage 1.b") {
steps {
catchError(buildResult: 'UNSTABLE', stageResult: 'FAILURE') {
bat "echo Stage 1.b" // Should not fail
}
}
post {
failure  {
script {
env.stageTwoFailed = "true"
}
}
}
}
}
}

stage("Stage 2") {
parallel {
// Only run stages if earlier steps didn't fail
stage("Stage 2.a") {
when {
environment(name: "stageOneFailed", value: "false")
}
steps {
catchError(buildResult: 'UNSTABLE', stageResult: 'FAILURE') {
bat "echo Stage 2.a"
}
}
post {
failure  {
script {
env.stageOneFailed = "true"
}
}
}
}
stage("Stage 2.b") {
when {
environment(name: "stageTwoFailed", value: "false")
}
steps {
catchError(buildResult: 'UNSTABLE', stageResult: 'FAILURE') {
bat "echo Stage 2.b"
}
}
post {
failure  {
script {
env.stageTwoFailed = "true"
}
}
}
}
}
}
}
}

但是当运行这个例子时,阶段1.a失败了,但阶段2.a仍然在运行,也许任何人都可以在这里提供帮助。。

编辑:我添加了输出,看看stageNFailed设置为什么值。即使在调用env.stageOneFailed之后,进入下一阶段时,它也会使用旧值false。。

我的假设是,当调用脚本env.stageNFailed=";真";,该值仅为该阶段临时设置。。

您使用的示例是完全可以接受的方法。您引入了2个env变量,用于确定上一步是否失败。您已经使用catchError来确保管道在阶段失败时不会失败。您必须在每个阶段使用catchError来防止管道失败(但我想您已经知道了(。在阶段的post部分中,您已经将适当的env变量设置为true,这也是正确的。

post {
failure {
script {
env.stageOneFailed = true
}
}
}

然后,当下一个相关阶段开始时,您已经使用when条件来检查该阶段是否应该运行(您也可以这样做(:

when {
expression { stageOneFailed == false }
}

所以基本上你做的每件事都是对的。

最新更新