Configuration

To configure available Groovy installation on your system, go to Jenkins configuration page, find section 'Groovy' and fill the form as shown bellow.

If you don't configure any Groovy installation and select (Default) option in a job, the plugin will fallback into calling just the groovy command, assuming you have groovy binary on the default path on given machine.

Usage

To create Groovy-based project, add new free-style project and select "Execute Groovy script" in the Build section, select previously configured Groovy installation and then type your command, or specify your script file name. In the second case path taken is relatively from the project workspace directory.

Jenkins 1.x:

Jenkins 2.x:

The plugin also adds the functionality of the Script Console to the project configuration page.

You can schedule your system management script...

...and then observe progress in the build log.

Groovy Script vs System Groovy Script

The plain "Groovy Script" is run in a forked JVM, on the slave where the build is run. It's the basically the same as running the "groovy" command and pass in the script.

The system Groovy script on the other hand runs inside the Jenkins master's JVM. Thus it will have access to all the internal objects of Jenkins, so you can use this to alter the state of Jenkins. It is similar to the Jenkins Script Console functionality.

Security

System groovy jobs has access to whole Jenkins, therefore only users with admin rights can add system Groovy build step and configure the system Groovy script. Permissions are not checked when the build is triggered (i.e. also uses without admin rights can also run the script). The idea is to allow users run some well defined (defined by admin) system tasks when they need it (e.g. put slave offline/online, when user wants to start some debugging on slave). To have Jenkins instance secure, the support for Token macro plugin has to be switched off, see section below.

Token macro plugin support

By default, the support for token macro pressing is switched off and has to be switch on in global config page.

If token macro processing via Token Macro Plugin is allowed, the evaluation of macro is done in System Groovy, therefore any user can run arbitrary system script, regardless he has administer permission!

Known bugs

Configuring more builders at once actually doesn't absolutely work. If you need more groovy builders in your project, you have to configure them one by one and always save project configuration before you add new one.

45 Comments

Thanks for this plugin. I've found one issue however (Windows server); if the path to a groovy script passes args, then the full string is quoted. For example, in the "Groovy script file" field, you may have, "build.groovy one two" ('one' and 'two' being args).

The call to groovy.bat will look like, C:\Groovy-1.5.4\bin\groovy.bat "c:\hudson\jobs\groovy\workspace\build.groovy one two"

The result is an exception because groovy.bat processes everything in quotes as one long filename:
Caught: java.io.FileNotFoundException: C:\hudson\jobs\groovy\workspace\build.groovy one two (C:\hudson\jobs\groovy\workspace\build.groovy one two

There is a hacky workound, after your build script name, put double quotes. In my example, build.groovy" one two . This closes the first double-quote, and the last added one gets ignored.

Ok, thank you for the information. One other thing I found if you're interested. Apparently 'groovy.bat' does not handle return codes well. So if you System.exit(1) for instance out of your 'groovy' code, Hudson will still report SUCCESS. It's not Hudson's fault, but groovy.bat. Some notes on the groovy web site mention that using the native launcher fixes this (groovy.exe versus groovy.bat). I downloaded your src and changed ".bat" to ".exe" and built the 'hpi' and it works such that my return codes are not ignored.

Wow, thanks for the fast fix. I'm mostly a linux guy, but have to support some Windows stuff. Speaking of, I tried out the plugin on linux, and tried my "hack" to pass parameters, but linux being stricter about quotes, the hack doesn't work. So I added a scriptArgs textbox under the scriptFile textbox and it works great. I tested giving the path to a groovy file with spaces in it on windows, and it quoted properly: e.g. <path-to-groovy.exe> "C:\Documents and Settings\user\build.groovy" -option1 -option2

The code is a little hacky as it's my first attempt at the plugin code, but I can get it to you if you're interested. Thanks again.

Unknown User (mindcrime)

Great plugin, thanks! A couple of questions though... Is running a groovy script different from running a groovy "system command" in terms of what "stuff" is exposed to the groovy code? That is, the example listed above doesn't work for me when run as a Groovy script.. can I not get access to the hudson internals when running a Groovy script? What can you access when running Groovy scripts? Do you have visibility into any of the Hudson information about the project, build, etc? If so, how is it exposed to the Groovy code?

Ok after reading your comment a second time I don't think that the link will solve the problem you have. It seams to be the same problem I had but I found a workaround yesterday (its not so nice but it is working):

This will get you the values the user entered for the latest build of the given job, if this is the currently running job you will get the parameter for currently running job (tested with hudson 1.351).

Is it possible to access the properties set by a parametrized build form within a "Execute System Groovy script" (file or when directly entered in the text box). I can access the properties in an external groovy script ("Execute Groovy script") by going over the System.getenv() path. But when trying the same inside a system one the properties are not set in the environment.

I tried to add the properties with the "Variable bindings" by specifying testName=$NameOfParameter but this is also not working. Basically the plugin is not resolving $NameOfParameter to the value of this field.

I think the simplest solution would just be to add the properties from the parametrized build to the environment of the groovy script.

Unknown User (vladimir d)

def job = Hudson.instance.getItem("JobName");
def envVars= job.lastBuild.properties.get("envVars"); // this is actually the currently running build, if the script is executed in "JobName"
println envVars["MyParameterName"];

I'd like to invoke (i.e. submit to the build queue) a parameterised job with two parameters, A and B. I'd like to invoke the job using the default value for A and supply an overridden value for B. I'd also like to wait for the submitted job to complete. Can anyone provide explicit code for doing this? Thanks.

Don't want to lost my script, may be somebody will need it. Lot of things this can do (most of copypaste part from another scripts some of them already on this page).

We have build jobs which only build code (job ends with "-build" suffix) and depoy jobs (the same name as build job, but "-CI" suffix).

Task was to determine does code already built (and skip build step which save time and resources because don't need to rerun build job again) otherwise to trigger build job, and then retrieve component version and trigger deployment tool (to pass arguments which WAR to deploy).

build job system groovy script:

Determines COMPONENT_VERSION from Maven, OR (!) if you specifu POM_XML=relativepath/pom.xml if will parse XML, in some cases it is correct way) - this step is merging of 2 separate scripts, which was before, now if option POM_XML injected via envinjector plugin - groovy runs xml parsin algorithm, otherwise just takes mavenVer from maven build result

Detetmines MAX_SVN_REVISION - It is already exist SVN_REVISION = SVN_REVISION_1 & SVN_REVISION_2,3,4 and so on, to make things simplier script compares all SVN_REVISION_N variables and choose the highest (may be to summarize them is more correct, but all works fine for now).

Determines does it release or *-SNAPSHOT version and set RELEASE=true/false accordingly. Needed only to skip Sonar which is always fails if release (releases goes with Artifactory plugin), so Sonar configured to skip itself if RELEASE=true

deploy job system groovy script:

Suggest build job name simply replacing -CI to -build suffix, but you have option to specify it manually (if build job is different from autosuggestion) -> just inject variable BUILD_JOB_NAME=buildjobname and script will use it.

Get COMPONENT_VERSION from last build job, which is setted up with prevous script.

Determines MAX_SVN_REVISION (see above) and compares it with the same from the last build job -> if this the same it don't triggers build job, because don't need to waste time to compile the same code twice (othewise it triggering build job)

Does anyone have a problem specifying classpath for a script using the class path edit box build option targeting Windows?

When I specify multiple jar files in the edit box, the script cannot import a Java class specified with 'import' statement. If I use -cp "jarfile1.jar;jarfile2.jar;jarfile3.jar" in the Groovy Parameters edit box, the script can import the specified class.

So it seems to me that quote around classpath is required on Windows, because using the class path edit box does work on Unices.

I had the need to create system groovy script to modify build parameters. I was unable to find a direct answer to my question through googling, so I thought I would deposit my solution here in hopes that it will find another who is in need.

In this case, I have one string type parameter that I want to programmatically alter. I don’t want to monkey with any of the other parameters .

import hudson.model.*
// get the original parameters as they were submitted
current_param_actions = build.getAction(ParametersAction.class)
def current_params = current_param_actions.getParameters()
// create a new empty set of parameters that will eventually contain our substituting value
Collection<? extends ParameterValue> new_params = new ArrayList<>();
// copy all the submitted parameters, except the one that we are altering
current_params.each() {
if ( ! it.getName().equals("NAME_OF_PARAM_TO_ALTER") ) {
new_params.add( it )
}
}
// determine new value of the parameter we wish to override and add it to our set of parameters
new_value = func_to_find_value()
new_params.add( new StringParameterValue("NAME_OF_PARAM_TO_ALTER", new_value ) )
// replace the submitted set of values with our altered set of values
build.actions.remove(current_param_actions)
new_param_actions = current_param_actions.createUpdated(new_params)
build.actions.add(new_param_actions)
// some debugging output for sanity checking when examining console output
build.getAction(ParametersAction.class).getParameters().each {
println "[info] parameter ${it.name}:"
println "[info] " + it.dump()
println "-" * 80
}

However, the system groovy script, which runs in the Jenkins JRE does not have ivy available to do that. I've heard that you could load the ivy jar into the Jenkins war to make this work, but it isn't a very viable option as you'll need to do it after each upgrade.

I've tried adding something like "/tmp/ivy-2.4.0-rc1.jar" to the classpath field but it doesn't make any difference. Looking through the plugin source code, it seems to apply this variable here in the SystemGroovy.java

when executing a Groovy script from a job. When I paste the command from the console into a prompt on the slave, it works fine. As I read on the net this migt be caused by setting GROOVY_HOME, but I don't do that (and setting it doesn't solve it)

does not work (anymore) with Jenkins 2.5. On an attempt to execute this code the following message is logged in the Jenkins console log:

May 19, 2016 11:10:24 AM hudson.model.ParametersAction filter
WARNING: Skipped parameter `BAR` as it is undefined on `test`. Set `-Dhudson.model.ParametersAction.keepUndefinedParameters`=true to allow undefined parameters to be injected as environment variables or `-Dhudson.model.ParametersAction.safeParameters=[comma-separated list]` to whitelist specific parameter names, even though it represents a security breach

Then there is no warning message in the log, but the attempt to refer (later in the job definition) the variable in a shell script reveals an empty value, i.e. the variable is not transferred to the build (defined outside the Groovy script)
Is there any workaround for this problem?

The answer to your question is in the error message you posted. This is related to a security update, that by default will block all parameters you create through groovy.

You can pass in these arguments inside the jenkins.xml

Set `-Dhudson.model.ParametersAction.keepUndefinedParameters`=true to allow undefined parameters
to be injected as environment variables or `-Dhudson.model.ParametersAction.safeParameters=[comma-separated list]`
to whitelist specific parameter names, even though it represents a security breach

Thanks for the plugin, it is helping us a lot. We have a groovy script which will execute as a post build step(system groovy script) in all our Jenkins jobs(300+). This groovy script requires few additional jar files to be available in classpath. So if we have any change in external jars versions, it is hard for us to configure these jars in all the jobs from plugin configuration. Can we have a option to add classpath jars at global level(manage jenkins) configuration?