问题
I'm using a declarative pipeline. This part works:
steps {
script {
if ('xxx' == 'cloud') {
sh 'xxx'
} else {
sh 'xxx'
}
}
}
But I want to follow the more declarative pipeline syntax using when. I tried something like this:
stage ('Newman run') {
when {
expression { "xxx" == "cloud" }
}
steps {
echo 'Use proxy for cloud'
sh 'xx'
}
when {
expression { "cloud" == "cloud" }
}
steps {
echo 'Do not use proxy (non-cloud)'
sh 'xxx'
}
But it didn't work. How I can specify a sort of 'else
' statement after a when
in a declarative pipeline. Or if this not works, the recommended way to do this?
回答1:
Possible duplicate of How to do simple if-statements inside a declarative pipeline in Jenkins
The first snippet you posted is a good way to go. You could use the 'not' directive in a second stage like this:
stage('then') {
when {
<condition>
}
steps {
...
}
}
stage('else') {
when {
not {
<condition>
}
}
steps {
...
}
}
But that doesn't look better than wrapping it in a 'script' statement, because you would even maintain the condition twice. And it's two separate stages that appear in your pipeline.
So stay with the if-then-else inside a script block.
Rationale: The idea of the declarative pipeline is to keep it simple without complex algorithms in it. When you are tempted to use if statements, loops, etc. in your Jenkinsfile, ask yourself if you are doing the right thing. Using these things if not wrong in general, but it could be that there is a simpler solution for your problem.
回答2:
Only one when
clause is allowed per stage
. You need two stage
s excluding each other by when
clauses to achieve the if-else behavior you want.
来源:https://stackoverflow.com/questions/48785761/how-to-perform-when-else-in-declarative-pipeline