Jenkins

How to Use Jenkins Groovy Script Console

In your Jenkins journey, you will encounter instances where you need advanced capabilities outside the scope of the provided Jenkins API. This is where the Jenkins Script Console comes into play.

The script console in Jenkins provides a means of executing Groovy scripts on the Jenkins server. Using the Groovy language, you can define a wide range of scripts, such as installing plugins, setting global variables, and performing other tasks that can be automated.

In this short tutorial, we will show you how you can use and execute Groovy Scripts on the Jenkins server using the Script Console.

It is good to keep in mind that this tutorial is not meant as an introduction to Jenkins or the Groovy scripting language.

How to Access the Jenkins Script Console

We can access the Jenkins console from the Jenkins Web interface. Select the Manage Jenkins option on the left-hand menu.

Navigate to the Tools and Actions section and select the “script console” option.

This will provide you with a text input area where you can provide your Groovy scripts to run on the server.

Example Groovy Script

The following is a simple Groovy script that Restarts the Jenkins server when no job is running.

import jenkins.model.*

def instance = Jenkins.getInstance()
if (instance.isQuietingDown()) {
   println 'Jenkins is already shutting down'
} else if (instance.isInFlight()) {
   println 'A build is currently in progress'
} else {
   instance.doSafeRestart()
   println 'Jenkins was restarted'
}

To run this script, copy and paste it into the script console and click the “Run” button.

The script will check to see if Jenkins is currently shutting down or if a build is in progress. If neither of these conditions is true, it will restart Jenkins. Otherwise, it will print a message indicating that the restart could not be performed.

Conclusion

You discovered how you can access and use the Jenkins Groovy script console to execute Groovy scripts on the Jenkins server.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list