How to Call A Groovy Script From A Jenkins File?

9 minutes read

To call a Groovy script from a Jenkins file, you can follow these steps:

  1. First, make sure you have the necessary plugins installed on your Jenkins server to support Groovy scripting.
  2. In your Jenkins pipeline or job, create a new stage or step where you want to call the Groovy script.
  3. Inside that stage or step, use the sh step to execute a shell command. Groovy scripts can be executed within a shell environment. stage('Call Groovy Script') { steps { sh ''' groovy myscript.groovy ''' } }
  4. Replace myscript.groovy with the path to your actual Groovy script.
  5. Save and run your Jenkins job or pipeline. Jenkins will execute the shell command, which in turn will call your Groovy script.


Remember to adjust the path or filename as per your specific setup. This method allows you to execute any Groovy script within your Jenkins pipeline or job file.

Best Groovy Books to Read in 2024

1
Programming Groovy: Dynamic Productivity for the Java Developer (Pragmatic Programmers)

Rating is 5 out of 5

Programming Groovy: Dynamic Productivity for the Java Developer (Pragmatic Programmers)

2
Programming Groovy 2: Dynamic Productivity for the Java Developer (Pragmatic Programmers)

Rating is 4.9 out of 5

Programming Groovy 2: Dynamic Productivity for the Java Developer (Pragmatic Programmers)

3
Mastering GROOVY: A Comprehensive Guide To Learn Groovy Programming

Rating is 4.8 out of 5

Mastering GROOVY: A Comprehensive Guide To Learn Groovy Programming

4
Groovy Programming: An Introduction for Java Developers

Rating is 4.7 out of 5

Groovy Programming: An Introduction for Java Developers

5
Making Java Groovy

Rating is 4.6 out of 5

Making Java Groovy

6
Groovy in Action: Covers Groovy 2.4

Rating is 4.5 out of 5

Groovy in Action: Covers Groovy 2.4


How to call a method from another groovy script in Jenkins?

To call a method from another Groovy script in Jenkins, follow these steps:

  1. Create a Groovy script containing the method you want to call. For example, define a method called myMethod() in a file called script1.groovy:
1
2
3
def myMethod() {
   // Method code here
}


  1. In your main Groovy script, import the method from the script1.groovy file. For example:
1
2
3
4
5
// Import the script containing the method
def script = load('path/to/script1.groovy')

// Call the method
script.myMethod()


Make sure to replace path/to/script1.groovy with the actual path to the script1.groovy file.

  1. Save and run the main Groovy script in Jenkins. It will call the myMethod() method from the script1.groovy file.


Note: Both the main script and the script containing the method should be accessible by Jenkins. You may need to consider configuring the Jenkins workspace or using a shared storage location for the scripts.


What is the syntax for a Jenkins pipeline?

The Jenkins Pipeline uses a Groovy-based DSL (Domain-Specific Language) for defining and managing the continuous delivery pipeline in Jenkins. Here is an example of the basic syntax for a Jenkins pipeline:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
pipeline {
    agent { 
        // Defines the agent where pipeline will run, such as 'node', 'docker', etc.
    }
    
    stages {
        stage('Stage 1') {
            steps {
                // Define the steps to be executed in this stage
            }
        }
        
        stage('Stage 2') {
            when {
                // Defines conditions when this stage should be executed, such as 'expression', 'not', etc.
            }
            steps {
                // Define the steps to be executed in this stage
            }
        }
    }
    
    post {
        always {
            // Define the steps to be executed regardless of the stages' success or failure
        }
        success {
            // Define the steps to be executed on successful completion of all stages
        }
        failure {
            // Define the steps to be executed on failure of any stage
        }
    }
}


This is just a basic structure, and you can customize it further based on your requirements. The agent block defines where the pipeline will execute, the stages block defines the individual stages and steps to be executed in each stage, and the post block defines steps to be executed after the completion of all stages.


How to call a groovy script from a Jenkins shared library?

To call a Groovy script from a Jenkins shared library, follow these steps:

  1. Create a Groovy script in the vars directory of your Jenkins shared library. This script should contain the code you want to execute.
  2. Define a variable in your script, which will be used to store the result of the script execution.
  3. Import the necessary classes or methods that your script requires for execution, such as Jenkins environment variables or pipeline steps.
  4. Use the imported classes or methods to write the logic of your Groovy script.
  5. Use the return statement to return the result of your Groovy script.
  6. Save and commit the changes to your shared library repository.
  7. In your Jenkins pipeline script, import the shared library using the @Library annotation at the top of your pipeline script.
  8. To call the Groovy script from the shared library, use the syntax libraryName.scriptName(params) in your pipeline script, where libraryName is the name of your shared library and scriptName is the name of the Groovy script you created in the vars directory. Add any necessary parameters within the parentheses.
  9. Assign the result of the script call to a variable, which you can then use for further processing or evaluation in your pipeline script.


Here is an example of how the code may look:


Groovy script in the shared library (vars/myScript.groovy):

1
2
3
4
5
6
7
8
9
def call(param) {
  // import necessary classes or methods
  def name = env.JOB_NAME

  // write script logic
  def result = param + " " + name

  return result
}


Jenkins pipeline script:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
@Library('my-shared-library') _

pipeline {
  agent any
  
  stages {
    stage('Run Script') {
      steps {
        script {
          // call the Groovy script from the shared library
          def scriptResult = myScript('Hello')
          echo "Result of script execution: ${scriptResult}"
        }
      }
    }
  }
}


Note: Replace my-shared-library with the actual name of your shared library.


How to execute a groovy script in Jenkins?

To execute a Groovy script in Jenkins, you can use either the "Execute Groovy script" step or the "Groovy Postbuild" plugin. Here are the steps for both methods:


Method 1: Using "Execute Groovy script" step

  1. Open your Jenkins job configuration.
  2. Scroll down to the "Build" section and click on the "Add build step" dropdown.
  3. Select "Execute Groovy script" from the options.
  4. In the "Groovy command" field, either write your Groovy script inline or specify the path to a script file.
  5. Click on "Save" to save the job configuration.
  6. Run the Jenkins job, and the Groovy script will be executed as part of the job.


Method 2: Using "Groovy Postbuild" plugin

  1. Install the "Groovy Postbuild" plugin from the Jenkins plugin manager. Go to "Manage Jenkins" > "Manage Plugins" > "Available" tab, search for "Groovy Postbuild", and install it.
  2. Open your Jenkins job configuration.
  3. Scroll down to the "Post-build Actions" section and click on the "Add post-build action" dropdown.
  4. Select "Groovy Postbuild" from the options.
  5. In the "Groovy script" field, either write your Groovy script inline or specify the path to a script file.
  6. Click on "Save" to save the job configuration.
  7. Run the Jenkins job, and the Groovy script will be executed as a post-build action.


Note: Make sure that the Jenkins server has the required Groovy environment configured and has Groovy installed.


What is the purpose of the Jenkins global library?

The purpose of the Jenkins global library is to create reusable code and functions that can be shared across multiple Jenkins pipelines. It allows developers to define common procedures, utilities, or custom steps as code, and make them available to every Jenkins pipeline run on the Jenkins instance. This promotes code reuse, maintainability, and standardization across the organization's pipeline projects. The global library can contain functions, classes, variables, and other code that can be used in Jenkins pipeline scripts.

Twitter LinkedIn Telegram Whatsapp

Related Posts:

To get Jenkins node configurations from Groovy, you can use the following steps:Open your Jenkins dashboard and navigate to "Manage Jenkins" from the left-hand side menu. Click on "Script Console" to open the script console. In the script conso...
To call a Gradle method from a Groovy script, you can follow these steps:Import the necessary Gradle classes at the beginning of the script: import org.gradle.api.Project Access the Gradle project object within your script: Project project = project Use the pr...
To iterate through an XML file in a Groovy script, you can follow these steps:Import required classes: Import the necessary classes for XML handling in Groovy by adding the following import statement at the top of your script: import groovy.util.XmlSlurper Rea...