简体   繁体   中英

How to re-use groovy script in Jenkins Groovy Post Build plugin?

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?

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.

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"))

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);
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM