How to create methods in Jenkins Declarative pipeline?

In Jenkins scripted pipeline we are able to create methods and can call them. Is it possible also in the Jenkins declarative pipeline? And how?

3,622 3 3 gold badges 40 40 silver badges 53 53 bronze badges asked Dec 4, 2017 at 7:15 vinesh vini vinesh vini 1,071 1 1 gold badge 8 8 silver badges 4 4 bronze badges Yes, this is possible. Commented Dec 4, 2017 at 7:21 Can you please share the syntax for that Thanks in advance Commented Dec 4, 2017 at 8:29 Jenkins Pipelines are Groovy-Scripts. So you just have to follow Groovy syntax. Commented Dec 4, 2017 at 8:39 Actually this was not possible with declarative pipelines until a few versions ago. Commented Dec 4, 2017 at 10:41 I would appreciate an example as scoping seems to have an effect. Commented Apr 6, 2018 at 13:08

4 Answers 4

Newer versions of the declarative pipelines support this, while this was not possible before (~mid 2017). You can just declare functions as you'd expect it from a groovy script:

pipeline < agent any stages < stage('Test') < steps < whateverFunction() >> > > void whateverFunction() < sh 'ls /' >
answered Dec 4, 2017 at 10:44 StephenKing StephenKing 37.3k 11 11 gold badges 87 87 silver badges 115 115 bronze badges

I was able to get this to work, however it removes the ability to edit the pipeline in the Blue Ocean GUI editor. Do you know of a way around that? I do most of the editing in the Jenkinsfile directly via text editor, but it is nice to be able to stub things out quickly in the UI. I got around that by commenting out the function temporarily.

Commented Mar 18, 2018 at 21:03

I'm trying to define a function that defines a stage but this doesn't seem to work (syntax error expected 'stage'). Do they only support running functions defining steps?

Commented Jun 1, 2018 at 0:16

This is really cool. However, where is this documented? I fail to find any resource describing this ability. I only find documentation how to import external, shared groovy libraries. I only find this SO answer for embedding them in the Jenkinsfile itself, which is really useful. Jenkins issue tracker with proposals received wontfix status, e.g.: issues.jenkins-ci.org/browse/JENKINS-41396

Commented Aug 14, 2018 at 10:09

@WillBrode i am also interested in having functions to define/configure an entire stage. It is my understanding that the declarative pipeline parser simply doesn't allow those type of syntax flexibility: issues.jenkins-ci.org/browse/JENKINS-49135 Have you had any success with this?

Commented Jan 16, 2020 at 16:58

@carlos I asked that question and there are some answers here: stackoverflow.com/questions/50634592/…