How to create methods in Jenkins Declarative pipeline?

JenkinsGroovyJenkins PipelineJenkins GroovyJenkins Declarative-Pipeline

Jenkins Problem Overview


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?

Jenkins Solutions


Solution 1 - Jenkins

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 - Jenkins

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 - Jenkins

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

Solution 4 - Jenkins

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
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionvinesh viniView Question on Stackoverflow
Solution 1 - JenkinsStephenKingView Answer on Stackoverflow
Solution 2 - JenkinslvthilloView Answer on Stackoverflow
Solution 3 - JenkinsawefsomeView Answer on Stackoverflow
Solution 4 - JenkinsMukesh MView Answer on Stackoverflow