0
0
Jenkinsdevops~5 mins

Groovy methods in pipelines in Jenkins - Commands & Configuration

Choose your learning style9 modes available
Introduction
Jenkins pipelines use Groovy code to automate tasks. Groovy methods help organize repeated steps into reusable blocks, making pipelines cleaner and easier to manage.
When you want to run the same set of steps multiple times in a pipeline without repeating code.
When you need to break a complex pipeline into smaller, understandable parts.
When you want to pass parameters to a block of code to customize its behavior.
When you want to improve pipeline readability by naming logical groups of steps.
When you want to reuse code across different stages or jobs in Jenkins.
Config File - Jenkinsfile
Jenkinsfile
pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                script {
                    def greet(name) {
                        echo "Hello, ${name}!"
                    }
                    greet('World')
                }
            }
        }
    }
}

This Jenkinsfile defines a pipeline with one stage called 'Example'. Inside the stage, a Groovy method named greet is declared using def. This method takes a parameter name and prints a greeting message. The method is then called with the argument 'World'.

This shows how to define and use Groovy methods inside the script block of a Jenkins pipeline.

Commands
Check that Jenkins Job Builder or Jenkins CLI is installed and accessible before running pipelines.
Terminal
jenkins-jobs --version
Expected OutputExpected
2.0.0
Trigger the Jenkins pipeline named 'example-pipeline' and wait for it to finish to see the output.
Terminal
jenkins-cli build example-pipeline -s
Expected OutputExpected
[Pipeline] Start of Pipeline [Pipeline] stage [Pipeline] { (Example) [Pipeline] script [Pipeline] echo Hello, World! [Pipeline] } [Pipeline] // stage [Pipeline] End of Pipeline Finished: SUCCESS
-s - Waits for the build to complete and shows the console output.
Key Concept

If you remember nothing else from this pattern, remember: Groovy methods let you group and reuse pipeline steps to keep your Jenkinsfile clean and easy to read.

Common Mistakes
Defining Groovy methods outside the script block in a declarative pipeline.
Declarative pipelines require Groovy code like method definitions to be inside the script block; otherwise, Jenkins will fail to parse the pipeline.
Always define Groovy methods inside a script block within your pipeline stages.
Calling a Groovy method before it is defined in the script block.
Groovy methods must be defined before they are called; otherwise, Jenkins throws a missing method error.
Define the method first, then call it later in the script block.
Summary
Define Groovy methods inside the script block of Jenkins pipeline stages.
Use methods to group repeated or complex steps for better readability.
Call methods after defining them to reuse code and pass parameters.