Sling Academy
Home/DevOps/Using Jenkins with Groovy scripts: A Practical Guide (with examples)

Using Jenkins with Groovy scripts: A Practical Guide (with examples)

Last updated: February 03, 2024

Introduction

Jenkins, one of the leading open-source automation servers, provides an extensive platform for automating the distribution of software. Groovy, a powerful language for the Java platform, adds flexibility and power to Jenkins, making your CI/CD pipeline more dynamic and responsive. This guide will take you through the basics to more advanced uses of Groovy scripts in Jenkins, with practical examples to reinforce your understanding.

Getting Started with Jenkins and Groovy

Before diving into Groovy scripting within Jenkins, it is essential to have Jenkins installed and running. Visit the official Jenkins website for installation instructions. Similarly, familiarize yourself with Groovy by visiting the Groovy website.

Basic Groovy Scripting for Jenkins

Let’s start with a simple Groovy script to print “Hello, World” in a Jenkins Pipeline:

pipeline {
    agent any
    stages {
        stage('Hello World') {
            steps {
                script {
                    println('Hello, World')
                }
            }
        }
    }
}

This is a declarative Pipeline script. The println statement is Groovy’s way of printing a line of text, similar to Java’s System.out.println.

Accessing Jenkins Objects

In a more practical scenario, you might want to use Groovy to access and manipulate Jenkins objects. Here’s how you can list all jobs on your Jenkins server:

for (item in Jenkins.instance.items) {
    println(item.name)
}

This script uses the Jenkins.instance object to access all items (jobs) and prints their names. Remember, to run Groovy scripts accessing Jenkins internals, you must have administrative privileges on the Jenkins server.

Parameterized Jenkins Jobs with Groovy

Let’s enhance our script to make our Jenkins job accept parameters. The following example demonstrates creating a string parameter:

pipeline {
    agent any
    parameters {
        string(
            name: 'GREET',
            defaultValue: 'Hello',
            description: 'Greeting'
        )
    }
    stages {
        stage('Greet') {
            steps {
                script {
                    echo "${params.GREET}, World"
                }
            }
        }
    }
}

This code snippet adds a parameter GREET to the pipeline, which can be customized when the pipeline is triggered.

Processing JSON with Groovy in Jenkins

Handling JSON data is a common requirement. Suppose you need to parse a JSON string and print its values. First, include the JSON library at the beginning of your script:

@Grab(group='org.json', module='json', version='20200518')

Then, you can parse and manipulate the JSON string as follows:

import org.json.JSONObject

def jsonString = '{"name":"John", "age":30}'
def json = new JSONObject(jsonString)

println(json.getString("name")) // Prints John
println(json.getInt("age"))    // Prints 30

Advanced Jenkins Groovy Scripting

Accessing System Environment Variables

You can access environment vars from Groovy using System.getenv:

def path = System.getenv('PATH') println("PATH: ${path}") 

Manipulating Strings and Files

Groovy’s powerful string manipulation capabilities can be very useful in Jenkins scripts. Here is how to read a file and print its content:

new File('/path/to/your/file.txt').eachLine { line -> println(line) } 

Using Groovy for Scripted Pipeline Decisions

In a more complex pipeline, you might want to make decisions based on logic. For example, you could execute different stages based on the day of the week:

pipeline {
    agent any
    stages {
        stage('Weekday Check') {
            steps {
                script {
                    def day = new Date().format('E')
                    if (day == 'Sat' || day == 'Sun') {
                        echo 'Weekend! Skipping the build.'
                    } else {
                        echo 'Weekday. Proceeding with the build.'
                    }
                }
            }
        }
    }
}

Conclusion

Groovy scripting within Jenkins provides an immensely powerful toolset for automating, customizing, and optimizing your CI/CD workflows. As we’ve seen from basic to advanced examples, with Groovy, almost anything is possible, allowing for a level of dynamism and responsiveness that is hard to achieve with other tools. Start small, master the basics, and gradually explore the extensive capabilities of Groovy in Jenkins to revolutionize your build pipelines.

Previous Article: Jenkins: How to set a timeout for a build

Series: Jenkins Tutorials

DevOps

You May Also Like

  • How to reset Ubuntu to factory settings (4 approaches)
  • Making GET requests with cURL: A practical guide (with examples)
  • Git: What is .DS_Store and should you ignore it?
  • NGINX underscores_in_headers: Explained with examples
  • How to use Jenkins CI with private GitHub repositories
  • Terraform: Understanding State and State Files (with Examples)
  • SHA1, SHA256, and SHA512 in Terraform: A Practical Guide
  • CSRF Protection in Jenkins: An In-depth Guide (with examples)
  • Terraform: How to Merge 2 Maps
  • Terraform: How to extract filename/extension from a path
  • JSON encoding/decoding in Terraform: Explained with examples
  • Sorting Lists in Terraform: A Practical Guide
  • Terraform: How to trigger a Lambda function on resource creation
  • How to use Terraform templates
  • Understanding terraform_remote_state data source: Explained with examples
  • Jenkins Authorization: A Practical Guide (with examples)
  • Solving Jenkins Pipeline NotSerializableException: groovy.json.internal.LazyMap
  • Understanding Artifacts in Jenkins: A Practical Guide (with examples)
  • Using Jenkins with AWS EC2 and S3: A Practical Guide