我有Jenkins管道,包括两个阶段,
我想仅在某些条件下执行第二阶段,例如如果git branch不是master。
当它在bash上时我常常使用简单的逻辑:
if [condition] {exit 0} else {stage2 function} fi
Jenkins管道如何实现groovy?
我的Jenkins文件看起来像这样 -
pipeline {
agent any
stages {
stage ('First') {
steps {
echo "First"
}
if (env.BRANCH_NAME == 'master') {
echo 'First stage is enought, exit 0 shoul happened here'
currentBuild.result = 'SUCCESS'
return
} else {
echo 'Second stage must be executed'
}
}
stage('Second') {
steps {
echo "Second"
}
}
}
}
但是,它在脚本管道中按预期工作 - https://github.com/kagarlickij/jenkins-pipeline/blob/scripted/Jenkinsfile
答案 0 :(得分:1)
exit 0
只会退出当前阶段而不是完整管道。这就是为什么我会推荐以下解决方法(我使用参数,但你当然也可以使用env var):
pipeline {
agent any
parameters {
string(defaultValue: "master", description: 'What branch?', name: 'BRANCH')
}
stages {
stage ('First') {
when {
expression
{ params.BRANCH == 'master' }
}
steps {
echo "Branch is master"
}
}
stage('Second') {
when {
expression
{ params.BRANCH != 'master' }
}
steps {
echo "Branch is not master"
}
}
}
}
参数:" master":
[Pipeline] {
[Pipeline] stage
[Pipeline] { (First)
[Pipeline] echo
Branch is master
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Second)
Stage 'Second' skipped due to when conditional
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
参数"与master不同的东西":
[Pipeline] {
[Pipeline] stage
[Pipeline] { (First)
Stage 'First' skipped due to when conditional
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Second)
[Pipeline] echo
Branch is not master
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
答案 1 :(得分:1)