简体   繁体   中英

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. So I have a little groovy script, which returns the remote 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? I can't use the EnvInject-plugin with the pipeline-plugin :(

Here is the little script for getting the 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.

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. 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)

// 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.

So from your pipeline just call def trigger = ipTrigger(currentBuild)

The the ipaddress will be, trigger.ip (sorry for the bad naming, couldn't come up with something original)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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