我可以使用闭包来定义 Jenkins 声明式管道中的阶段吗? [英] Can I use a Closure to define a stage in a Jenkins Declarative Pipeline?

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

问题描述

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

def makeStage = {阶段('a'){脚步 {回声你好世界"}}}管道{代理无阶段{制作阶段()}}

但它给了我这个例外:

WorkflowScript: 11: 需要一个阶段@第 11 行第 5 列.制作阶段()^

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

解决方案

您不能在声明性管道之外定义阶段.声明式管道的主要目的是提供简化和固执己见的语法,以便您可以专注于应该做什么(通过使用一些可用的 步骤)而不是如何去做.

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

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

#!groovydef makeStage = {阶段('a'){回声你好世界"}}节点{制作阶段()}

<块引用>

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

java.lang.NoSuchMethodError: No such DSL method 'steps' found between步骤 [存档,bat,构建,catchError,结帐,deleteDir,目录,dockerFingerprintFrom, ...

声明性管道中的脚本

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

I'm trying to do something like this:

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

But it gives me this exception:

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.

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()
}

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, ...

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.

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

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