我有一个阶段,它在一个阶段中,我想根据when中的条件跳过它-
pipeline {
agent any
stages {
stage("Dynamic stages") {
steps {
script {
serverAStatus = false
def tests = CLIENTS.split(',')
def builders = [:]
for (test in tests) {
def test1 = test
builders[test] = {
stage("Test ${test1}") {
when {
expression {
(serverAStatus && (test1.equals("ABC") || test1.equals("XYZ")))
}
}
node('master') {
script {
echo "Executing stage ${test1}"
echo "Client is " + test1
}
}
}
}
}
parallel builders
}
}
}
}
}但这会产生错误- No such DSL method when inside steps
我尝试在stage中使用if语句,而不是when,比如-
if ((!serverAStatus && (test1.equals("ABC") || test1.equals("XYZ")))) {
echo "******************************************************"
Utils.markStageSkippedForConditional(STAGE_NAME)
}但这并不能跳过这个阶段。
请帮助我如何在我的场景中跳过阶段。
发布于 2020-03-31 05:07:44
首先,为了消除一些误解,在script步骤中定义一个stage实际上是有效的。这是一种将阶段动态添加到声明性管道的常见模式。
在script步骤中,适用脚本化管道的规则。脚本化管道有一个stage函数,它不需要steps,甚至不需要script子函数。脚本化stage中的所有内容也使用脚本化语法。
您可以简单地使用GroovyGroovy语句跳过脚本阶段:
script {
if( serverAStatus && (test1.equals("ABC") || test1.equals("XYZ")) ) {
stage('A Stage') {
echo 'Hello'
}
}
}这有一个缺点,那就是阶段将从蓝海管道视图中完全缺少。
我们真正想要的是显示stage,但是处于跳过的状态,因为我们是从声明性管道中使用的。这可以使用imperative when step (相关blog post)来实现。
结果并不完美,因为Blue Ocean将在舞台上绘制一条直线(而不是舞台周围的曲线),但stage按钮表示跳过的状态。
在包含了blog post中描述的共享库之后,我们现在可以这样写:
script {
stage("Test ${test1}") {
when( serverAStatus && (test1.equals("ABC") || test1.equals("XYZ")) ) {
echo 'Hello'
}
}
}下面是使用“命令式when”重写的完整示例,并删除了一些过时的代码:
pipeline {
agent any
stages {
stage("Dynamic stages") {
steps {
script {
serverAStatus = false
def tests = CLIENTS.split(',')
def builders = [:]
for (test in tests) {
def test1 = test
builders[test] = {
stage("Test ${test1}") {
when( serverAStatus && (test1.equals("ABC") || test1.equals("XYZ")) ) {
node('master') {
echo "Executing stage ${test1}"
echo "Client is " + test1
}
}
}
}
}
parallel builders
}
}
}
}
}为了样本的缘故,node('master')也可以被移除。我把它留在原处,因为您可能希望在多个节点上并行运行并行阶段。在这种情况下,您可以使用公共节点标签替换'master‘,或者根据变量test1传递显式的节点名称。
发布于 2020-03-30 19:13:51
这里发生的情况是,您在声明性管道中编写了一个脚本化管道。它们的语法略有不同,when约束仅适用于声明性约束。
试着在脚本中写这段代码:
pipeline {
agent any
stages {
stage("Dynamic stages") {
steps {
script { // inside this block, scripted pipeline syntax only
serverAStatus = false // note that no tests will run
def tests = CLIENTS.split(',')
def builders = [:]
for (test in tests) {
def test1 = test
if (serverAStatus && (test1.equals("ABC") || test1.equals("XYZ"))) {
builders[test1] = {
node('master') {
script {
echo "Executing stage ${test1}"
echo "Client is " + test1
}
}
}
}
}
parallel builders
}
}
}
}
}https://stackoverflow.com/questions/60928388
复制相似问题