繁体   English   中英

如何在Jenkins Groovy Post Build插件中重用groovy脚本?

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

我有一些groovy代码,我打算在多个作业的Jenkins Groovy Post Build插件中重复使用。 我怎样才能做到这一点? 有没有一个地方我可以将脚本存储在一个全局变量中,并在我需要的工作中调用它?

您可以在groovy postbuild中加载生活在Jenkins主服务器上的任何groovy文件并执行它。 例如,您可以在c驱动器上有一个特殊目录,其中包含所有常用脚本。 稍后我将使用一些代码更新我的答案,该代码向您展示如何加载脚本。

更新

假设您的C:驱动器上有一个test.groovy文件,它应该像Groovy Postbuild中的以下内容一样简单:

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

请查看Groovy Postbuild的评论部分以获取更多示例和其他可能的方法。

这是适合我的解决方案:

  1. 为Jenkins安装了Scriptler插件并保存了Groovy脚本。 现在该脚本在JENKINS_HOME/scriptler/scripts目录中可用。 这样我们就可以避免手动将文件复制到Jenkins master。
  2. 在Post build中使用了groovy文件:

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

这是我对StackOverflow上类似问题的回答的副本:

如果您希望在代码存储库中安装Groovy脚本,并将其加载到工作区中的构建/测试从属服务器上,那么您需要注意Groovy Postbuild在主服务器上运行。

对我们来说,主服务器是Unix服务器,而构建/测试从服务器是本地网络上的Windows PC。 因此,在使用脚本之前,我们必须打开从主服务器到从服务器的通道,并使用FilePath到该文件。

以下为我们工作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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