Accessing the current Jenkins build in Groovy script

useful jenkins groovy scripts
jenkins groovy script examples
jenkins groovy script parameters
groovy script to parse jenkins console output
jenkins groovy script create job
jenkins groovy get build number
jenkins groovy build job
jenkins get job build status

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.

The current build is required when using an Hudson.model Cause.UpstreamCause to link the current build of my current job to a dependent job that I am scheduling.

Since code is more concise:

my-job-step.groovy:

def scheduleDependentJob(jobName) {
  def fooParam = new StringParameterValue('foo', 'bar');
  def paramsAction = new ParametersAction(fooParam)

  println "Scheduling dependent job"
  def currentJob = ???
  def cause = new Cause.UpstreamCause(currentBuild)
  def causeAction = new hudson.model.CauseAction(cause)
  instance.queue.schedule(job, 0, causeAction, paramsAction)
}

The CauseAction constructor (Seen on http://javadoc.jenkins-ci.org/hudson/model/Cause.UpstreamCause.html) requires a Run object, which the current build object should be an instance of. I just can't find a good way to get the current running job build inside of a Groovy script.

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

Groovy, Jenkins features a Groovy script console which allows one to run arbitrary Groovy It can even read files in which the Jenkins master has access to on the host ( like In the following example somescript.groovy is a groovy script in the current Allow broken build claiming on every jobs — With the following simple script,� That’s how I ended up writing groovy script for Jenkins. We can get the details of one more build jobs from jenkins by writing groovy scripts. Jenkins has script console option to execute groovy

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

Script Console, Jenkins has script console option to execute groovy scripts on its server. So let's get started… Here we will try to get the details of only job. We� I have a groovy script that goes and promotes code. Long story short, I know at a point of time within that script if it was successful or not. I would like to fail the build if not successful. Is there a way in groovy to fail the build? Example: in the "execute Groovy script" plugin. you can write code.

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

Writing groovy script for Jenkins, Retrieve parameters of the current build def foo = build. that's because the groovy script isn't running in the same process as the Jenkins job� Additionally, the implementors of Jenkins Pipeline found Groovy to be a solid foundation upon which to build what is now referred to as the "Scripted Pipeline" DSL. [ 2 ] . As it is a fully-featured programming environment, Scripted Pipeline offers a tremendous amount of flexibility and extensibility to Jenkins users.

Jenkins & Groovy – accessing build parameters – RucialK, Runs docker build to create and tag the specified image from a Dockerfile in the current directory. BUILD_NUMBER: The current build number, such as "153"; BUILD_ID: The As an example of loading variable values from Groovy: build, offers access to a map of defined build variables; for a Pipeline downstream build ,� Here I am using groovy script plugin to take the build status and setting it to the environmental variable, so the environmental variable can be used in post-build scripts using post-build task plugin. Groovy script:-import hudson.EnvVars import hudson.model.Environment def build = Thread.currentThread().executable def result = manager.build

Pipeline Syntax: Global Variable Reference [Jenkins], This Groovy tutorial for Jenkins will show you how to use Apache Groovy script to build a Jenkins pipeline. Groovy is suitable for beginners and is a good It has seamless integration with all existing Java objects and libraries. Groovy is Java without types, Accessing steps � Shared library Groovy classes� To make this easier, your Pipeline’s Jenkinsfile can be written in a text editor or integrated development environment (IDE) and committed to source control (optionally with the application code that Jenkins will build). Jenkins can then check out your Jenkinsfile from source control as part of your Pipeline project’s build process and then

Tutorial: Jenkins Pipeline file with Apache Groovy, Actively fail current pipeline job, error("Build failed because of this and that. scripts, COPY config/*.groovy /usr/share/jenkins/ref/init.groovy.d/. Configure Jenkins url: jenkins-url.groovy: Create a Jenkins user: create-jenkins-user.groovy: Groovy manages files/folders: files-folder.groovy: Configure max executors in Jenkins: master-executors.groovy: Configure only 1 executor per worker: For each agent, configure # of executors: Configure slack plugin: config-slack.groovy: Configure

Comments
  • I found YMMV a bit depending on what calls the groovy script (e.g. email-ext-plugin, post-build actions). With running jobs 'activeBuild = Thread.currentThread().executable' works. With old jobs that doesn't work. Using the predefined var build is probably best IF it is there. To get the build object in both cases you can do something like 'try { c = build.getClass() } catch(Exception ex) { try { build = Thread.currentThread().executable } catch(Exception ex2) { println("oh dear, no build object.")} }'.