[英]Can I use a Closure to define a stage in a Jenkins Declarative Pipeline?
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. 如果您对更灵活的实现管道的方式感兴趣,您可以选择Scripted Pipeline方法,如果涉及到语法,则该方法并不严格 - 它仅受Groovy和CPS执行模块的限制。
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 insidestage
in a scripted pipeline. 注意 :脚本管道中的stage
内没有steps
方法。 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, ...
Declarative pipeline defines a script
step that allows you to put a block of scripted pipeline. 声明性管道定义了一个script
步骤 ,允许您放置一个脚本化管道块。 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. script
步骤在舞台内执行,因此如果执行舞台,则无法控制此块内部。 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. 但是,在某些情况下,如果您想要执行比调用声明性管道的预定义步骤更复杂的操作,则此步骤可能非常有用。
Super late, but in case anyone runs into this issue, a possible solution would be to wrap your generated stage around a script declarative and invoke .call
on the generated stage. 超级晚了,但是如果有人遇到这个问题,可能的解决方案是将生成的阶段包装在脚本声明中并在生成的阶段调用.call
。
So for you: 所以对你来说:
def makeStage = { return { stage('a') { echo 'Hello World' } } } pipeline { agent none stages { stage ('hello world') { steps { script { makeStage().call() } } } } }
Whoops. 哎呦。 edited, I had "steps" inside on my stage('a') in the makeStage declaration. 编辑,我在makeStage声明中的舞台('a')里面有“步骤”。 "steps" is a declarative pipeline directive so it was throwing an error inside the script block. “steps”是一个声明性管道指令,因此它在脚本块中抛出一个错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.