How to create methods in Jenkins Declarative pipeline?

92,627

Solution 1

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 /'
}

Solution 2

You can create a groovy function like this and save it in your git which should be configured as managed library (Configure it in jenkins too):

/path/to/repo-shared-library/vars/sayHello.groovy:

Content:

def call(String name = 'human') {
    echo "Hello, ${name}."
}

You can just call this method in your pipeline using:

@Library('name-of-shared-library')_
pipeline {
    agent any
    stages {
        stage('test') {
            steps {
                sayHello 'Joe'
            }
        }
    }
}

Output:

[Pipeline] echo
Hello, Joe.

You can reuse existing functions which you keep in your library.

Solution 3

This worked for me.It can be view with Blue Ocean GUI but when I edit using Blue Ocean GUI it removes methods "def showMavenVersion(String a)".

pipeline {
agent any
stages {
    stage('build') {
        agent any
        steps {
            script {
                showMavenVersion('mvn version')
            }
        }
    }
}

}

def showMavenVersion(String a) {
        bat 'mvn -v'
        echo a
}

Solution 4

You can also have separate groovy files with all your functions (just to keep things structured and clean), which you can load to file with pipeline:

JenkinsFile.groovy

Map modules = [:]
pipeline {
    agent any
    stages {
        stage('test') {
            steps {
                script{
                    modules.first = load "first.groovy"
                    modules.first.test1()
                    modules.first.test2()
                }
            }
        }
    }
}

first.groovy

def test1(){
    //add code for this method
}
def test2(){
    //add code for this method
}
return this
Share:
92,627
vinesh vini
Author by

vinesh vini

Updated on June 25, 2020

Comments

  • vinesh vini
    vinesh vini almost 4 years

    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?

  • Damon
    Damon about 6 years
    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.
  • Will Brode
    Will Brode almost 6 years
    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?
  • gertvdijk
    gertvdijk over 5 years
    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
  • Benjamin Vison
    Benjamin Vison over 5 years
    I can't seem to find the answer to "Step does not take a single required parameter - use named parameters instead", I am getting this error exactly at the method call
  • carlos
    carlos over 4 years
    @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?
  • Will Brode
    Will Brode over 4 years
    @carlos I asked that question and there are some answers here: stackoverflow.com/questions/50634592/…
  • ealeon
    ealeon over 3 years
    what if you want to have multiple functions in a groovy? or is it recommended to have one groovy per function?
  • lvthillo
    lvthillo over 3 years
    @ealeon you can have multiple functions in the shared library and call them from inside your pipeline
  • YoavKlein
    YoavKlein over 3 years
    Can you explain the return this statement? Why is that necessary?
  • macetw
    macetw over 3 years
    This could also be made more clear by defining exactly where each file is saved, relative to one another.
  • Veaceslav Serghienco
    Veaceslav Serghienco over 3 years
    jenkins.io/doc/pipeline/steps/workflow-cps i guess load "first.groovy" will execute the groovy script, and "return this" will return reference to the script it self which contains the methods otherwise you won't get the reference to the methods.
  • Marteng
    Marteng over 3 years
    Is it possible to e.g. move stage('build') into the showMavenVersion method?
  • Eric Salemi
    Eric Salemi over 2 years
    Such method is not usable in a post block even though documentation here says we can use steps.
  • StephenKing
    StephenKing over 2 years
    @EricSalemi you have to wrap the call in script { } I guess.