我可以使用Closure在Jenkins声明性管道中定义一个阶段吗? [英] Can I use a Closure to define a stage in a Jenkins Declarative Pipeline?

查看:209
本文介绍了我可以使用Closure在Jenkins声明性管道中定义一个阶段吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做这样的事情:

I'm trying to do something like this:

def makeStage = {
  stage('a') {
    steps {
      echo 'Hello World'
    }
  }
} 
pipeline {
  agent none
  stages {
    makeStage()
  }
}

但这给了我这个例外:

WorkflowScript: 11: Expected a stage @ line 11, column 5.
   makeStage()
   ^

是否可以将阶段定义为外部闭包?如果是,如何?

Is it possible to define a stage as a external closure and if so - how?

推荐答案

您不能在声明式管道之外定义阶段.声明性管道的主要目的是提供简化且自以为是的语法,以便您可以专注于应做的事情(通过使用一些可用的步骤),而不是操作方法.

You can't define stages outside the declarative pipeline. The main purpose of declarative pipeline is to provide simplified and opinionated syntax so you can focus on what should be done (by using some of the available steps) and not how to do it.

如果您对更灵活的管道实现方式感兴趣,可以选择脚本化管道方法在语法方面没有那么严格-仅受Groovy和CPS执行模块的限制.

If you are interested in more flexible way of implementing pipeline, you may choose Scripted Pipeline approach which is not that strict if it comes to the syntax - it's only limited by Groovy and CPS execution module.

示例中的工作(脚本化)管道如下所示:

Working (scripted) pipeline from your example would look like this:

#!groovy

def makeStage = {
  stage('a') {
    echo 'Hello World'
  }
} 

node {
    makeStage()
}

注意:脚本管道中的stage内部没有任何steps方法.如果你把它留在那里,你会得到

Attention: There is no steps method inside stage in a scripted pipeline. If you leave it there you will get

java.lang.NoSuchMethodError: No such DSL method 'steps' found among 
    steps [archive, bat, build, catchError, checkout, deleteDir, dir, 
    dockerFingerprintFrom, ...

声明性管道中的脚本

声明性管道定义了script步骤,该步骤可让您放置一段脚本化的管道.但是,它仍然不允许您动态定义阶段或/和/或将阶段定义提取到函数或闭包中. script步骤在阶段内部执行,因此无论阶段是否执行,您都无法在此块内进行控制.但是,在某些情况下,如果您想做一些比仅调用声明性管道的预定义步骤更复杂的事情,则此步骤可能非常有用.

Scripts in declarative pipeline

Declarative pipeline defines a script step that allows you to put a block of scripted pipeline. However it still does not allow you to define stage dynamically or/and extract stage definition to a function or closure. script step gets executed inside the stage so you can't control inside this block if stage is executed or not. In some cases however this step might be very useful if you want to do something more complex than just calling pre-defined step of a declarative pipeline.

这篇关于我可以使用Closure在Jenkins声明性管道中定义一个阶段吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆