4
votes

I have some groovy code which I am planning to re-use in Jenkins Groovy Post Build plugin of multiple jobs. How can I achieve this? Is there a place I can store the script in a global variable and call that in the jobs where ever I need?

3

3 Answers

2
votes

You can load any groovy file living on the Jenkins master within the groovy postbuild and execute it. For example, you could have a special directory on the c drive where all the common scripts live. I'll update my answer later with some code that shows you how to load the script in.

Update

Assuming you have a test.groovy file on your C: drive, it should be as simple as the following in Groovy Postbuild:

evaluate(new File("C:\\test.groovy"))

Please view the comment section of the Groovy Postbuild for more examples and possibly other ways.

1
votes

Here is the solution that worked for me:

  1. Installed Scriptler plugin for Jenkins and saved the Groovy script in that. Now the script is available in JENKINS_HOME/scriptler/scripts directory. This way we can avoid manual step of copying files to Jenkins master.
  2. Used the groovy file in Post build:

def env = manager.build.getEnvironment(manager.listener) evaluate(new File(env['JENKINS_HOME'] + "\\scriptler\\scripts\\GroovyForPostBuild.groovy"))

1
votes

This is a copy of my answer to this similar question on StackOverflow:

If you wish to have the Groovy script in your Code Repository, and loaded onto the Build / Test Slave in the workspace, then you need to be aware that Groovy Postbuild runs on the Master.

For us, the master is a Unix Server, while the Build/Test Slaves are Windows PCs on the local network. As a result, prior to using the script, we must open a channel from the master to the Slave, and use a FilePath to the file.

The following worked for us:

// Get an Instance of the Build object, and from there
// the channel from the Master to the Workspace
build = Thread.currentThread().executable
channel = build.workspace.channel;

// Open a FilePath to the script
fp = new FilePath(channel, build.workspace.toString() + "<relative path to the script in Unix notation>")

// Some have suggested that the "Not NULL" check is redundant
// I've kept it for completeness
if(fp != null)
{
    // 'Evaluate' requires a string, so read the file contents to a String
    script = fp.readToString();
    // Execute the script
    evaluate(script);
}