Issue
I want to automate the use of some Jenkins features that are not available via the REST API. Can I run Groovy in the Jenkins script console via a REST request or Jenkins CLI?
Environment
-
CloudBees CI (CloudBees Core) on modern cloud platforms - Managed controller
-
CloudBees CI (CloudBees Core) on modern cloud platforms - Operations Center
-
CloudBees CI (CloudBees Core) on traditional platforms - Client controller
-
CloudBees CI (CloudBees Core) on traditional platforms - Operations Center
-
CloudBees Jenkins Enterprise - Managed controller
-
CloudBees Jenkins Enterprise - Operations center
-
CloudBees Jenkins Distribution
Resolution
Jenkins supports scripting with the Groovy language. A Jenkins admin user can get a scripting console by opening in a browser the URL /script
of your Jenkins instance. (i.e: https://jenkins.example/script
). Reference Script Console.
Besides, users with admin permission can execute groovy code remotely and this article is going through the diferent available options. To explain the different options we are using the same script (system-message-example.groovy
) as an example, which updates the System Message
from Manage Jenkins
> Configure System
.
import jenkins.model.Jenkins message="foo" Jenkins jenkins = Jenkins.get() jenkins.setSystemMessage(message) jenkins.save()
To automate the execution of the above script, save it to a file (let’s say system-message-example.groovy
).
Via REST API
Reading the script
curl --data-urlencode "script=$(cat /tmp/system-message-example.groovy)" -v --user username:ApiToken https://jenkins.example.com/scriptText
Introducing the script manually and separate by ;
curl --data-urlencode "script=message='foo'; Jenkins jenkins = Jenkins.get(); jenkins.setSystemMessage(message); jenkins.save()" -v --user username:ApiToken https://jenkins.example.com/scriptText
Via Jenkins CLI
The following examples uses the jenkins-cli
alias as explained here.
groovy
It requires a script passed as parameter
$> jenkins-cli groovy = < /tmp/system-message-example.groovy
groovysh
It creates an interactive groovy shell, where you need to type every line of the script.
jenkins-cli groovysh Groovy Shell (2.4.12, JVM: 1.8.0_252) Type ':help' or ':h' for help. ------------------------------------------------------------------------------- groovy:000> import jenkins.model.Jenkins ===> hudson.model.*, jenkins.model.Jenkins groovy:000> message="foo" ===> foo groovy:000> Jenkins jenkins = Jenkins.get() ===> hudson.model.Hudson@42694fdc groovy:000> jenkins.setSystemMessage(message) ===> null groovy:000> jenkins.save() ===> null groovy:000>