简体   繁体   English

使用Groovy脚本在jenkins管道中注入变量

[英]Inject variable in jenkins pipeline with groovy script

I am building a jenkins pipeline and the job can be triggered by remote. 我正在建立一个詹金斯管道,这项工作可以由远程触发。 I have the requirement to know which IP triggered the job. 我需要知道哪个IP触发了这项工作。 So I have a little groovy script, which returns the remote IP. 因此,我有一个简单的脚本,它返回了远程IP。 With the EnvInject-plugin I can easily use this variable in a normal freestyle job, but how can I use this in the pipeline scirpt? 使用EnvInject-plugin,我可以轻松地在常规的自由式作业中使用此变量,但是如何在管道脚本中使用它呢? I can't use the EnvInject-plugin with the pipeline-plugin :( 我不能将EnvInject-plugin与管道插件一起使用:(

Here is the little script for getting the IP: 这是获取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]

You can create a shared library function (see here for examples and the directory structure). 您可以创建一个共享库函数(有关示例和目录结构,请参见此处 )。 This is one of the undocumented (or really hard to find any documentation) features of Jenkins. 这是Jenkins的未记录(或者很难找到任何文档)功能之一。

If you would put a file triggerIp.groovy in the directory vars , which is in the directory workflow-libs at the root level of JENKINS_HOME and put your code in that file. 如果您将文件triggerIp.groovy放在目录vars ,该目录位于JENKINS_HOME根目录下的目录workflow-libs中,然后将代码放入该文件中。 The full filename then will be $JENKINS_HOME/workflow-libs/vars/ipTrigger.groovy (You can even make a git repo for your shared libraries and clone it in that directory) 完整的文件名将是$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]
}

After a restart of Jenkins, from your pipeline script, you can call the method by the filename you gave it. 重新启动Jenkins之后,可以从管道脚本中通过给它的文件名调用该方法。

So from your pipeline just call def trigger = ipTrigger(currentBuild) 因此,从您的管道中只需调用def trigger = ipTrigger(currentBuild)

The the ipaddress will be, trigger.ip (sorry for the bad naming, couldn't come up with something original) ipaddress将是trigger.ip (抱歉,命名错误,无法提供原始内容)

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

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