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

4

我有一些 Groovy 代码,打算在多个 Jenkins Groovy Post Build 插件中重复使用。我应该怎么做呢?是否有地方可以将脚本存储在全局变量中,并在需要的作业中调用它?

3个回答

2
你可以在Groovy Postbuild中加载Jenkins主机上的任何groovy文件并执行它。例如,你可以在c盘上有一个特殊目录,其中包含所有常见脚本。稍后我将更新我的答案,并展示如何加载脚本的一些代码。 更新 假设您在C:驱动器上有一个test.groovy文件,那么只需在Groovy Postbuild中执行以下操作即可:
evaluate(new File("C:\\test.groovy"))

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

谢谢。这个解决方案帮了我一半的忙。以下是我所做的,使它成为一个完整的解决方案: - rkkreddy
我认为你的评论被截断了,因为我没有看到解决方案... 如果你愿意,你可以把你的解决方案作为另一个答案添加进来,然后接受它作为你问题的最终解决方案... 这可能会对其他人有所帮助。如果我的答案对你有帮助,请随意给它点个赞吧。 :) - Daniel Omoto

1
这是我在StackOverflow上回答类似问题的副本:
如果您希望将Groovy脚本放入代码库,并加载到工作区中的构建/测试Slave中,则需要知道Groovy Postbuild在Master上运行。
对我们来说,主服务器是Unix服务器,而构建/测试Slaves是本地网络上的Windows PC。因此,在使用脚本之前,我们必须从主服务器打开通道到Slave,并使用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);
} 

1
这是对我有用的解决方案:
  1. 安装Jenkins的Scriptler插件,并将Groovy脚本保存在其中。现在脚本可以在JENKINS_HOME/scriptler/scripts目录中使用,这样我们就可以避免手动复制文件到Jenkins主节点。
  2. 在后置构建中使用Groovy文件:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接