簡體   English   中英

使用Groovy腳本在jenkins管道中注入變量

[英]Inject variable in jenkins pipeline with groovy script

我正在建立一個詹金斯管道,這項工作可以由遠程觸發。 我需要知道哪個IP觸發了這項工作。 因此,我有一個簡單的腳本,它返回了遠程IP。 使用EnvInject-plugin,我可以輕松地在常規的自由式作業中使用此變量,但是如何在管道腳本中使用它呢? 我不能將EnvInject-plugin與管道插件一起使用:(

這是獲取IP的小腳本:

import hudson.model.*
import static hudson.model.Cause.RemoteCause


def ipaddress=""
for (CauseAction action : currentBuild.getActions(CauseAction.class)) {

    for (Cause cause : action.getCauses()) {
        if(cause instanceof RemoteCause){
             ipaddress=cause.addr
             break;
        }
    }
}
return ["ip":ipaddress]

您可以創建一個共享庫函數(有關示例和目錄結構,請參見此處 )。 這是Jenkins的未記錄(或者很難找到任何文檔)功能之一。

如果您將文件triggerIp.groovy放在目錄vars ,該目錄位於JENKINS_HOME根目錄下的目錄workflow-libs中,然后將代碼放入該文件中。 完整的文件名將是$JENKINS_HOME/workflow-libs/vars/ipTrigger.groovy (您甚至可以為共享庫制作一個git repo並將其克隆到該目錄中)

// workflow-libs/vars/ipTrigger.groovy
import hudson.model.*
import static hudson.model.Cause.RemoteCause

@com.cloudbees.groovy.cps.NonCPS
def call(currentBuild) {
    def ipaddress=""
    for (CauseAction action : currentBuild.getActions(CauseAction.class)) {

        for (Cause cause : action.getCauses()) {
            if(cause instanceof RemoteCause){
                ipaddress=cause.addr
                break;
            }
        }
    }
    return ["ip":ipaddress]
}

重新啟動Jenkins之后,可以從管道腳本中通過給它的文件名調用該方法。

因此,從您的管道中只需調用def trigger = ipTrigger(currentBuild)

ipaddress將是trigger.ip (抱歉,命名錯誤,無法提供原始內容)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM