Accessing the current Jenkins build in Groovy script

后端 未结 3 1993
攒了一身酷
攒了一身酷 2021-02-14 06:09

I have created a Groovy script which is used in a System Groovy Script step in a Jenkins job which needs to access the current build of the current job.

T

相关标签:
3条回答
  • 2021-02-14 06:30

    If in your Jenkins job you are using Groovy plug-in, then inside Execute system Groovy script step the plug-in already provides you access to some predefined variables:

    build
        The current AbstractBuild.
    launcher
        A Launcher.
    listener
        A BuildListener.
    out
        A PrintStream (listener.logger).
    

    For example:

    println build.getClass()
    

    Outputs:

    class hudson.model.FreeStyleBuild
    
    0 讨论(0)
  • 2021-02-14 06:30

    This is the snippet I have been looking for!

    import hudson.model.*
    def currentBuild = Thread.currentThread().executable
    

    This fits in with my above script like so:

    import hudson.model.*
    
    
    def scheduleDependentJob(jobName) {
      def fooParam = new StringParameterValue('foo', 'bar');
      def paramsAction = new ParametersAction(fooParam)
    
      println "Scheduling dependent job"
      def currentBuild = Thread.currentThread().executable
      def cause = new Cause.UpstreamCause(currentBuild)
      def causeAction = new hudson.model.CauseAction(cause)
      instance.queue.schedule(job, 0, causeAction, paramsAction)
    }
    
    0 讨论(0)
  • 2021-02-14 06:44

    This completes the answer from luka5z to exemplify how scriptler passes the listener to the groovy script:

    import jenkins.model.*;
    import hudson.model.*;
    import hudson.util.*;
    import hudson.tasks.*;
    import hudson.plugins.git.*;
    import hudson.scm.*
    import jenkins.scm.*
    
    def build = Thread.currentThread()?.executable
    //def svn_branch = build.buildVariableResolver.resolve("SVN_BRANCH")
    
    if (build instanceof AbstractBuild){
        def workspace = build.workspace
        //def job = build.parent
        def scm = build.parent.scm;
        //println "scm: $scm"
    
        if (scm instanceof hudson.scm.SubversionSCM) {
            scm.checkout(build, null/*Launcher*/, workspace /*workspace*/, listener/*listener*/, null /*changelogfile*/,null/*baseline*/)
        }else if (scm instanceof hudson.plugins.git.GitSCM) {
            scm.checkout(build, null/*Launcher*/, workspace /*workspace*/, listener/*listener*/, null /*changelogfile*/,null/*baseline*/)
        }
    }
    

    listener in Scriptler

    0 讨论(0)
提交回复
热议问题