如何中止声明式管道

How to abort a declarative pipeline

我正在尝试新的声明性管道语法。

我想知道,例如当某个参数具有无效值时,我如何才能中止管道的所有阶段和步骤。

我可以在每个阶段添加一个 when 子句,但这对我来说不是最佳选择。有更好的方法吗?

这在 when directive, if you make use of the error 步骤中应该可以正常工作。

例如,如果给定的参数值不可接受,您可以进行前期检查并中止构建 - 防止后续阶段 运行:

pipeline {
  agent any
  parameters {
    string(name: 'targetEnv',
           defaultValue: 'dev',
           description: 'Must be "dev", "qa", or "staging"')
  }
  stages {
    stage('Validate parameters') {
      when {
        expression {
          // Only run this stage if the targetEnv is invalid
          !['dev', 'qa', 'staging'].contains(params.targetEnv)
        }
      }
      steps {
        // Abort the build, skipping subsequent stages
        error("Invalid target environment: ${params.targetEnv}")
      }
    }
    stage('Checkout') {
      steps {
        echo 'Checking out source code...'
      }
    }
    stage('Build') {
      steps {
        echo 'Building...'
      }
    }
  }
}

您可以使用 FlowInterruptedException,例如:

import hudson.model.Result
import org.jenkinsci.plugins.workflow.steps.FlowInterruptedException

pipeline {
  ...
  steps {
    script {
      throw new FlowInterruptedException(Result.ABORTED)
    }
  ...
}

这将像 error 步骤一样立即停止执行,但可以更好地控制结果。

请注意,它需要您批准签名

new org.jenkinsci.plugins.workflow.steps.FlowInterruptedException hudson.model.Result

除了Result.ABORTED还有:Result.SUCCESSResult.UNSTABLEResult.FAILUREResult.NOT_BUILT

免责声明:有点乱。