簡體   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