Manage Jenkins Using Script Console

Nilkumar Shah
Globant
Published in
7 min readFeb 19, 2024

A few months ago, I used Jenkins’ user interface. It’s a handy tool for creating and managing our projects, checking build reports, and setting up project plugins, among other tasks. This process went smoothly until I created a couple of projects and managed them using the Jenkins user interface. But things became difficult when we needed to create and manage hundreds of projects using the user interface. This turned into a tedious and time-consuming task for the team.

While looking for other options, I found out that using a script console to manage Jenkins makes tasks easier and saves a lot of time.

Here, I’ll explain how we can use the Jenkins script console to save time. Instead of doing the same tasks again and again on the Jenkins user interface, we can use the script console to do them faster.

We will walk through the process of creating jobs, adding new agents, and executing scripts in Jenkins using the Script Console.

Installation

Before we start understanding about Groovy script, install and start Jenkins on your machine. Here are the quick links for you to get started

Script Console

After you finish installing, open Jenkins in your web browser and go to http://localhost:8080/script. This will open the script console, where you can type Groovy code.

Before we start writing our first script, let’s understand what is script console is -

The Script Console in Jenkins is a special tool that helps you talk to Jenkins using a language called Groovy. Its importance lies in several key aspects:

  • The Script Console enables the automation of various Jenkins tasks by allowing us to write Groovy scripts. This is especially helpful for tasks that involve doing the same setup over and over again or when you need to do it for lots of projects.
  • The Script Console allows us to perform bulk operations on Jenkins jobs, nodes, or configurations. For instance, you can use scripts to make, change, or remove many jobs all at once. This saves you a lot of time and work.
  • We can run scripts to inspect the state of Jenkins objects, identify issues, or validate configurations. This helps in diagnosing problems and finding solutions quickly.
  • The Script Console complements the Jenkins ecosystem by providing a programmatic interface for interacting with other Jenkins components, plugins, and integrations.

Let’s now take the example of creating a simple Jenkins project using the Jenkins user interface. Then, we will create the same project using the script console.

Creating Jenkins job using UI

Creating a Jenkins job using the UI is a straightforward process. Here are the steps:

  1. Log in to Jenkins:
    - Open your web browser and navigate to the Jenkins instance (e.g., http://localhost:8080).
    - Log in using your credentials.
  2. Access the Jenkins Dashboard:
    - Once logged in, you’ll land on the Jenkins dashboard. This is the main page where you can view existing jobs and manage Jenkins.
  3. Click on “New Item”:
    - On the left-hand side, you’ll find a menu. Click on the “New Item” option. If you don’t see this option, look for a “+” button.
  4. Enter Job Name:
    - In the “Enter an item name” field, provide a name for your Jenkins job. This should be a unique and descriptive name that reflects the purpose of the job.
  5. Select Job Type:
    - Choose the type of job you want to create. For a basic build job, select “Freestyle project.” There are other options, like pipeline jobs, for more advanced use cases.
  6. Configure Job:
    - You’ll be directed to the configuration page for your new job. Here, you can set various parameters and configurations for your job. Some common configurations include:
    - General
    - Source Code Management (SCM)
    - Build Triggers: Specify conditions that trigger a build, such as code commits or scheduled builds.
    - Build Environment: Define the build environment settings.
    - Build: Configure the build steps. This could include running shell commands, executing a script, or using build tools.
    - Post-build Actions: Define actions to be taken after the build, such as archiving artifacts or sending notifications.
  7. Save the Job Configuration:
    -
    Once you’ve configured your job, scroll down and click the “Save” button to save your job configuration.

This should create a Job in your Jenkins dashboard, following the same process with some additional steps based on project requirements becomes a tedious job when we start working with larger/complex projects.

Basics of Groovy scripting

Groovy is a strong and flexible programming language. It’s commonly used for scripting within Java-based programs. Jenkins uses Groovy as its main scripting language, especially in tools such as the Script Console and Pipeline DSL. These tools are really important because they help make both Declarative and Scripted Pipelines. These pipelines are essential for building and managing projects in Jenkins. Here are the basics of Groovy:

  • Groovy supports meta-programming, which means you can change or add to how classes work while your program is running.
def name = "Groovy"
def age = 10
  • Groovy scripts don’t require a class definition, so you can write scripts without the boilerplate code typically needed in languages like Java.
println("Hello, World!")
  • Groovy supports string interpolation, allowing you to embed expressions within strings.
def name = "World"
println("Hello, $name!")
  • Groovy provides a concise syntax for working with lists and maps.
  • Closures are a powerful feature in Groovy. They are similar to anonymous functions or lambdas in other languages.
  • The safe navigation operator (?.) allows you to safely access properties or methods of an object, avoiding null pointer exceptions.
  • Groovy supports meta-programming, allowing you to modify or extend the behaviour of classes dynamically.
  • Groovy seamlessly integrates with existing Java code. You can use Java libraries and classes in Groovy scripts and vice versa.
  • Groovy provides a convenient syntax for file I/O operations, making it easy to work with files.

Creating a job using Groovy script

Creating a Jenkins job using a Groovy script can be done through the Jenkins Script Console or by using the Jenkins Job DSL plugin. Here, I’ll provide an example using the Script Console. This script will create a Freestyle project job. You can adjust it according to your specific requirements.

You can run the below script in the Jenkins script console (http://localhost:8080/script)

import Jenkins.model.*
import Hudson.model.*

// Define job parameters
def jobName = "YourJobName"
def jobDescription = "Your job description"
def scmURL = "https://github.com/your/repo.git"
def scmBranch = "master"
def buildScript = "echo 'Hello, Jenkins!'"

// Create a new project
def project = Jenkins.instance.createProject(FreeStyleProject, jobName)

// Configure job settings
project.setDescription(jobDescription)

// Add SCM configuration (Git in this example)
def scm = new hudson.plugins.git.GitSCM([
new hudson.plugins.git.UserRemoteConfig(scmURL, null, null, null)
])
project.setScm(scm)
project.getBuildersList().add(new hudson.tasks.Shell(buildScript))

// Save the project
project.save()

// Print job creation success message
println("Jenkins job '$jobName' created successfully.")

Please visit the Jenkins dashboard to see the created job.

Adding a New Agent Using Groovy Script

To add a new agent in Jenkins using Groovy, you can create either a traditional DumbSlave or a newer JNLPLauncher for a Java Web Start (JNLP) agent. Below is an example script for adding a new agent using the DumbSlave method. Adjust the parameters as needed for your environment.

import hudson.model.*
import hudson.slaves.*

// Define agent parameters
def agentName = "YourAgentName"
def agentDescription = "Your agent description"
def remoteFS = "/path/to/agent/workspace"
def labels = "linux docker"
def numExecutors = 2

// Create a new agent
def agent = new DumbSlave(
agentName,
"",
remoteFS,
numExecutors,
Node.Mode.NORMAL,
labels,
new JNLPLauncher(),
new RetentionStrategy.Always(),
new ArrayList<NodeProperty<Node>>()
)

// Add agent to Jenkins
Jenkins.instance.addNode(agent)

// Print agent creation success message
println("Jenkins agent '$agentName' added successfully.")

Advanced Operations

Feel free to customise this basic script according to your project needs. You can add extensions and integrate third-party plugins as required.

Advantages of using Groovy script in your project

Using Groovy scripts to create Jenkins jobs has several benefits. It gives you flexibility and automation and lets you manage job setups with code. Here are some pros of using Groovy scripts for Jenkins job creation:

  • Automation and Reproducibility
  • Version Control
  • Code Reusability
  • Dynamic Configurations
  • Programmatic Job Manipulation
  • Batch Job Creation
  • Consistency Across Environments
  • Integration with External Systems

Cons of using Groovy script

Using Groovy scripts to make jobs in Jenkins gives you a lot of power and flexibility. However, there are also some challenges you should be aware of. Here are some cons associated with creating jobs using Groovy scripts:

  • Complexity for Beginners
  • Limited Visibility and Discoverability
  • Error-Prone Syntax
  • Security Concerns
  • Limited Support for All Job Configurations
  • Maintenance Challenges
  • Debugging Complexity

Resources

Here are some resources that can help you further understand and work with Jenkins Groovy scripting

Conclusion

When we think about the good and not-so-good parts of using a script console, we realize it’s a powerful tool. It helps us save time and makes us super efficient, especially when we have to do the same things over and over again. Even though there are a few downsides, using Groovy scripts turns out to be a smart and effective way to manage Jenkins.

Drop your comments, feedback, or suggestions below — or connect with me directly.

Thanks, and Happy coding ✌️

By Nilkumar Shah

--

--