Script Console
Jenkins features a Groovy script console which allows one to run arbitrary Groovy scripts within the Jenkins controller runtime or in the runtime on agents.
It is very important to understand all of the following points because it affects the integrity of your Jenkins installation. The Jenkins Script Console:
Because of the power offered by the Jenkins Script Console, Jenkins and its
agents should never be run as the Be sure to secure your Jenkins instance |
Multiple contexts
The Jenkins Script Console can run either on the controller or any configured agents.
Running Script Console on the controller
This feature can be accessed from "Manage Jenkins" > "Script Console".
Or by visiting the sub-URL /script
on your Jenkins instance.
Running Script Console on agents
Visit "Manage Jenkins" > "Manage Nodes". Select any node to view the status page. In the menu on the left, a menu item is available to open a "Script Console" on that specific agent.
Run scripts from controller Script Console on agents
It’s also possible to run scripts from the controller Script Console on individual agents. The following script is an example running a script on agents from the controller Script Console.
Script executes code on agent from Master Script Console
import hudson.util.RemotingDiagnostics
import jenkins.model.Jenkins
String agentName = 'your agent name'
//groovy script you want executed on an agent
groovy_script = '''
println System.getenv("PATH")
println "uname -a".execute().text
'''.trim()
String result
Jenkins.instance.slaves.find { agent ->
agent.name == agentName
}.with { agent ->
result = RemotingDiagnostics.executeGroovy(groovy_script, agent.channel)
}
println result
Reading and writing files
Files can be read and written directly on the controller or agents via the controller Script Console.
Write a file to the Jenkins controller
new File('/tmp/file.txt').withWriter('UTF-8') { writer ->
try {
writer << 'hello world\n'
} finally {
writer.close()
}
}
Reading a file from the Jenkins controller
new File('/tmp/file.txt').text
Write file to agent through agent channel
import hudson.FilePath
import hudson.remoting.Channel
import jenkins.model.Jenkins
String agentName = 'some-agent'
String filePath = '/tmp/file.txt'
Channel agentChannel = Jenkins.instance.slaves.find { agent ->
agent.name == agentName
}.channel
new FilePath(agentChannel, filePath).write().with { os ->
try {
os << 'hello world\n'
} finally {
os.close()
}
}
Read file from agent through agent channel
import hudson.FilePath
import hudson.remoting.Channel
import jenkins.model.Jenkins
import java.io.BufferedReader
import java.io.InputStreamReader
import java.nio.charset.StandardCharsets
import java.util.stream.Collectors
String agentName = 'some-agent'
String filePath = '/tmp/file.txt'
Channel agentChannel = Jenkins.instance.slaves.find { agent ->
agent.name == agentName
}.channel
String fileContents = ''
new FilePath(agentChannel, filePath).read().with { is ->
try {
fileContents = new BufferedReader(
new InputStreamReader(is, StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"))
} finally {
is.close()
}
}
// print contents of the file from the agent
println '==='
println(fileContents)
println '==='
Remote access
A Jenkins Admin can execute groovy scripts remotely by sending an HTTP POST
request to /script/
url or /scriptText/
.
curl example via bash
curl -d "script=<your_script_here>" https://jenkins/script
# or to get output as a plain text result (no HTML)
curl -d "script=<your_script_here>" https://jenkins/scriptText
Also, Jenkins CLI
offers the possibility to execute groovy scripts remotely using
groovy
command or execute groovy interactively via groovysh
.
However, once again curl can be used to execute groovy scripts by making
use of bash command substitution. In the following example
somescript.groovy
is a groovy script in the current working
directory.
Curl submitting groovy file via bash
curl --data-urlencode "script=$(< ./somescript.groovy)" https://jenkins/scriptText
If security is configured in Jenkins, then curl can be provided options to
authenticate using the curl --user
option.
Curl submitting groovy file providing username and api token via bash
curl --user 'username:api-token' --data-urlencode \
"script=$(< ./somescript.groovy)" https://jenkins/scriptText
Here is the equivalent command using python, not curl.
Python submitting groovy file providing username and api token
with open('somescript.groovy', 'r') as fd:
data = fd.read()
r = requests.post('https://jenkins/scriptText', auth=('username', 'api-token'), data={'script': data})
Shortcut key on script console to submit
You can submit a script without mouse. Jenkins has a shortcut key which enables to submit with keyboard.
-
Windows / Linux: Ctrl + Enter
-
Mac: Command + Enter
Video Tutorials and additional learning materials
Here are some recorded videos on the Jenkins Script Console:
-
Jenkins World 2017: Mastering the Jenkins Script Console - 44 minutes - sample usage and security discussion
-
LA Jenkins Area Meetup 2016 - Hacking on Jenkins Internals - Jenkins Script Console - 39 minutes - sample usage
To expand your ability to write scripts in the script console, the following references are recommended:
-
Learn Groovy - Learning Groovy is useful for more than writing scripts for the Script Console. Groovy is also relevant for other features of Jenkins like Pipelines and shared pipeline libraries, the Groovy Plugin, the Job DSL plugin, and many other plugins which utilize Groovy (see section [Plugins-enabling-Groovy-usage]).
-
Write Groovy scripts for Jenkins with Code completion - The gist of this is to create a Maven project within your IDE and to depend on org.jenkins-ci.main:jenkins-core (and any other plugins that you expect present). You can then write a Groovy script with code completion of Jenkins API objects and methods.
Example Groovy scripts
Out of date scripts
Due to the nature of Groovy scripts accessing Jenkins source code directly, Script Console scripts are easily out of date from the Jenkins source code. It is possible to run a script and get exceptions because public methods and interfaces in Jenkins core or Jenkins plugins have changed. Keep this in mind when trying out examples. Jenkins is easily started from a local development machine via the following command:
Starting a local copy of Jenkins
export JENKINS_HOME="./my_jenkins_home"
java -jar jenkins.war
Use CTRL+C to stop Jenkins. It is not recommended to try Script Console examples in a production Jenkins instance.
The following repositories offer solid examples of Groovy scripts for Jenkins.
Browse all https://plugins.jenkins.io/scriptler[Scriptler Plugin] Groovy Scripts and please share your scripts with the Scriptler Plugin.
-
Activate Chuck Norris Plugin — This script activates Chuck Norris plugin for all jobs in your Jenkins server
-
Add a Maven Installation, Tool Installation, Modify System Config
-
Add a new label to agents meeting a condition — This script shows how to alter the agent nodes' label membership. In this case we create a new label if the existing label contains a string. It has been tested from the Jenkins command window.
-
Add notification plugin to every job — This script will add the Notification Plugin to every job.
-
Allow broken build claiming on every jobs — With the following simple script, you can activate the option on every jobs of your server in just one go.
-
Batch-Update Mercurial branch that is checked out — Updates for multiple jobs which branch will be checked out from Hg
-
Change JVM Options in all Maven tasks of Freestyle Jobs — This script find all Maven Tasks registered in freestyle jobs and replace JVM Options by a new value.
-
Change SCMTrigger for each project to disable during the night and the week-end — This script lets you easily change all jobs running every minutes so that it gets disabled between 21:00 and 07:00 and on Saturday and Sunday.
-
Clone all projects in a View — This script enumerates all projects belonging to a specific view and clones them.
-
Convert standard mail notifications to use the Mail-Ext Publisher plugin — This script replace mail notifications in all projects by Mail-Ext publisher plugin and re-uses existing recipients.
-
Delete tmp files left in workspace-files — This scripts deletes all the tmp files left in workspace-files directory after the build. On windows servers this seems pretty common.
-
Delete workspace for all disabled jobs — Deletes the workspace for all disabled jobs to save space
-
Disable all jobs — This script disables all jobs in your Jenkins server
-
Display Information About Nodes — This scripts displays a bunch of information about all the agent nodes.
-
Display job parameters — This scripts displays the parameters for all the jobs along with their default values (if applicable).
-
Display list of projects that were built more than 1 day ago. — This script to display list of projects that were built more than 1 day ago.
-
Display mail notifications recipients — This script displays for all jobs the list of mail recipients used for notifications.
-
Display monitors status — Jenkins uses monitors to validate various behaviors. If you dismiss one, Jenkins will never propose you to reactivate it. This script allows you to check the status of all monitors and to reactivate them.
-
Display the number of jobs using SCM Polling from Freestyle, Pipeline and Maven
-
Display timer triggers — This scripts displays the timer triggers for all the jobs in order to better arrange them.
-
Display Tools Location on All Nodes — This script can help to get Jenkins tools location on all your agents
-
Enable Timestamper plugin on all jobs — With the following simple script, you can activate the option on every jobs of your server in just one go.
-
Failed Jobs — This scripts displays a list of all failed jobs. Addon: restart them.
-
Find builds currently running that has been executing for more than N seconds
-
Grant Cancel Permission for user and group that have Build permission — This script will go through all groups and users in both Global security and per job security settings.
-
Invalidate Jenkins HTTP sessions — This script can monitor and invalidate HTTP sessions if there are many open ones on your server.
-
Manually run log rotation on all jobs — Runs log rotation on all jobs to free space
-
Monitor and Restart Offline Agents — This script can monitor and restart offline nodes if they are not disconnected manually.
-
Monitoring Scripts — Several scripts to display data about http sessions, threads, memory, JVM or MBeans, when using the Monitoring plugin.
-
Parameterized System Groovy script — This script will demonstrate how to get parameters in a system groovy script.
-
Remove all disabled modules in Maven jobs — To remove all disabled modules in Maven jobs
-
Remove Deployed Artifacts Actions — This script is used to remove the Deployed Artifacts list that is uselessly stored for each build by the Artifact Deployer Plugin.
-
Remove Git Plugin BuildsByBranch BuildData — This script is used to remove the static list of BuildsByBranch that is uselessly stored for each build by the Git Plugin.
-
Set GitBlitRepositoryBrowser with custom settings on all repos — This scripts allows to update the repo browser. Can be adapted to any other browser, not only gitblit.
-
Update maven jobs to use the post build task to deploy artifacts — This script updates all maven jobs having a deploy goal by install and activate the post build step to deploy artifacts at the end of the build
-
Wipe out workspaces of all jobs — This script wipes out the workspaces of all jobs on your Jenkins server
-
Wipe workspaces for a set of jobs on all nodes — The script wipes workspaces of certain jobs on all nodes.
Plugins enabling Groovy usage
-
Config File Provider Plugin Adds the ability to provide configuration files (i.e., settings.xml for maven, XML, groovy, custom files, etc.) loaded through the Jenkins UI which will be copied to the job’s workspace.
-
Global Post Script Plugin — Execute a global configured groovy script after each build of each job managed by the Jenkins. This is typical for cases when you need to do something based on a shared set of parameters, such as triggering downstream jobs managed by the same Jenkins or remote ones based on the parameters been passed to the parameterized jobs.
-
Groovy Postbuild Plugin — This plugin executes a groovy script in the Jenkins JVM. Typically, the script checks some conditions and changes accordingly the build result, puts badges next to the build in the build history and/or displays information on the build summary page.
-
Groovy Remote Control Plugin — This plugin provides Groovy Remote Control's receiver, and allows to control external application from Jenkins.
-
Matrix Groovy Execution Strategy Plugin — A plugin to decide the execution order and valid combinations of matrix projects.
-
Scriptler Plugin — Scriptler allows you to store/edit groovy scripts and execute it on any of the nodes… no need to copy/paste groovy code anymore.