Child pages
  • Groovy Postbuild Plugin
Skip to end of metadata
Go to start of metadata

Plugin Information

Plugin ID



In Latest Release
Since Latest Release

Latest Release
Latest Release Date
Required Core

2.3.1 (archives)
Feb 07, 2016
workflow-cps (version:1.11, optional)
script-security (version:1.15)
matrix-project (version:1.4.1)

Source Code
Issue Tracking
Pull Requests

Open Issues
Pull Requests
Stefan Wolf (id: wolfs)
Serban Iordache (id: beryx)



2016-Nov 7907
2016-Dec 7753
2017-Jan 8264
2017-Feb 8480
2017-Mar 9038
2017-Apr 8915
2017-May 9369
2017-Jun 9661
2017-Jul 9845
2017-Aug 10229
2017-Sep 10352
2017-Oct 10584

Older versions of this plugin may not be safe to use. Please review the following warnings before using an older version:

This plugin executes a groovy script in the Jenkins JVM. Typically, the script checks some conditions and changes accordingly the build result, puts badges next to the build in the build history and/or displays information on the build summary page.

Migration from 1.X

From version 2.0, Groovy Postbuild plugin introduces Script Security Plugin.
Administrators can prevent users without proper privileges from running harmful scripts.
For details, see Script Security Plugin.
This doesn't affect Jenkins without security enabled and users with administrative privilege (to be exact, with RUN_SCRIPTS permission).

When you upgrade the Groovy Postbuild plugin from 1.X to 2.X, you and your Jenkins users
also requires update configurations of Groovy Postbuild, or they will fail with outputs like this:

ERROR: Failed to evaluate groovy script.
org.jenkinsci.plugins.scriptsecurity.scripts.UnapprovedUsageException: script not yet approved for use
	at org.jenkinsci.plugins.scriptsecurity.scripts.ScriptApproval.using(
	at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript.evaluate(
	at org.jvnet.hudson.plugins.groovypostbuild.GroovyPostbuildRecorder.perform(
	at hudson.tasks.BuildStepMonitor$1.perform(
	at hudson.model.AbstractBuild$AbstractBuildExecution.perform(
	at hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(
	at hudson.model.Build$BuildExecution.post2(
	at hudson.model.AbstractBuild$
	at hudson.model.Run.execute(
	at hudson.model.ResourceController.execute(

Scripts using only whitelisted methods of manager

Scripts using only whitelisted methods of manager can run with using Groovy sandbox.
They can be validated only by checking "Use Groovy Sandbox".

Scripts using non-whitelisted methods

Scripts using non-whitelisted methods of manager or methods not of manager requires
approval of administrators.

Administrators should check and approve those scripts in Manage Jenkins > In-process Script Approval.

Scripts using external jar files

If you refer external jar files from your scripts, you need to have those jar files approved by administartors.

Administrators should check and approve those jar files in Manage Jenkins > In-process Script Approval.

Scripts using external class directories

Script Security Plugin doesn't support class directories.

If you refer external class directories from your scripts, you should archive them into jar files.
It can be performed by running a following command:

jar -cf mylib.jar -C /path/to/classes .

You can use /path/to/mylib.jar as an additonal classpath for scripts.


The groovy script can use the variable manager, which provides various methods to decorate your builds.
Those methods can be classified into whitelisted methods and non-whitelisted methods.
You can always use Whitelisted methods, but you can use Non-whitelisted methods only when "Enable groovy postbuild security" is not enabled (version 1.X) or in scripts approved by administrators (since version 2.x)

Whitelisted methods

  • getEnvVariable(key) - get a variable value. (since 1.10)
  • getResult() - get a build result string (like SUCCESS, FAILURE) (since 2.2)
  • logContains(regexp) - returns true if the build log file contains a line matching regexp.
  • getLogMatcher(regexp) - returns a java.util.regex.Matcher for the first occurrence of regexp in the build log file.
  • addShortText(text) - puts a badge with a short text, using the default format.
  • addShortText(text, color, background, border, borderColor) - puts a badge with a short text, using the specified format.  For Colors supported, Google "html color names".
  • addBadge(icon, text) - puts a badge with the given icon and text. In addition to the 16x16 icons offered by Jenkins, groovy-postbuild provides the following icons (watch out for duplicates, see Example 5):

    - completed.gif
    - db_in.gif
    - db_out.gif
    - delete.gif
    - error.gif
    - folder.gif
    - green.gif
    - info.gif
    - red.gif
    - save.gif
    - success.gif
    - text.gif
    - warning.gif
    - yellow.gif

  • addBadge(icon, text, link) - like addBadge(icon, text), but the Badge icon then actually links to the given link (since 1.8)
  • addInfoBadge(text) - puts a badge with info icon and the given text.
  • addWarningBadge(text) - puts a badge with warning icon and the given text.
  • addErrorBadge(text) - puts a badge with error icon and the given text.
  • removeBadges() - removes all badges from the current build. It is often used with setBuildNumber.
  • removeBadge(index) - removes the badge with the given index. It is often used with setBuildNumber.
  • buildUnstable() - sets the build result to UNSTABLE.
  • buildFailure() - sets the build result to FAILURE.
  • buildSuccess() - sets the build result to SUCCESS.
  • buildIsA(klass) - test the build is a specified class (since 2.0)

Non-whitelisted methods

Methods returning non-primitive objects aren't whitelisted as groovy-postbuild doesn't ensure every methods of those objects are safe.

  • envVars - the build variables map. You can get a variable value with


    You shouldn't update values. This isn't whitelisted, and it is recommended to use getEnvVariable(key) instead. (since 1.10)

  • contains(file, regexp) - returns true if the given file contains a line matching regexp. Not whitelisted as it allows users access any files (for example, a file containing passwords).
  • getMatcher(file, regexp) - returns a java.util.regex.Matcher for the first occurrence of regexp in the given file.
  • setBuildNumber(number) - sets the build with the given number as current build. The current build is the target of all methods that add or remove badges and summaries or change the build result.
  • createSummary(icon) - creates an entry in the build summary page and returns a summary object corresponding to this entry. The icon must be one of the 48x48 icons offered by Jenkins. You can append text to the summary object by calling its appendText methods. Be careful appending HTML-unescaped texts as they can be harmful.
    • appendText(text, escapeHtml)
    • appendText(text, escapeHtml, bold, italic, color)
  • removeSummaries() - removes all summaries from the current build.
  • removeSummary(index) - removes the summary with the given index.

Rest interfaces

It is also possible to delete badges and summaries by using the following links:

  • remove all badges:
    • http://your-jenkins/job/your-job/build-number/parent/parent/plugin/groovy-postbuild/removeBadges
  • remove all summaries:
    • http://your-jenkins/job/your-job/build-number/parent/parent/plugin/groovy-postbuild/removeSummaries
  • remove the badge with the given index:
    • http://your-jenkins/job/your-job/build-number/parent/parent/plugin/groovy-postbuild/removeBadge?index=idx
  • remove the summary with the given index:
    • http://your-jenkins/job/your-job/build-number/parent/parent/plugin/groovy-postbuild/removeSummary?index=idx

Example usages

Example 1

The script below puts a warning badge and mark the build as unstable if it detects that deprecated methods were used.

if(manager.logContains(".*uses or overrides a deprecated API.*")) {
    manager.addWarningBadge("Thou shalt not use deprecated methods.")
    manager.createSummary("warning.gif").appendText("<h1>You have been warned!</h1>", false, false, false, "red")

Example 2

Suppose we have a parameterized build, which uses the boolean parameter storeToDB in order to instruct the build to store some artifacts into the database. The script below puts a badge next to the builds for which this parameter is set.

if("true".equals("storeToDB"))) {
    manager.addBadge("db_in.gif", "Stored to DB")

Example 3

Suppose we have a parameterized build, which uses the string parameter version. The script below puts a short text indicating the value of this parameter next to successful and unstable builds.

if( {

Example 4

The script below determines how long it took to build the project and displays the corresponding value as a short text next to each build.

def matcher = manager.getLogMatcher(".*Total time: (.*)\$")
if(matcher?.matches()) {
    manager.addShortText(, "grey", "white", "0px", "white")

Example 5

For badges, you can choose from the 16x16 icons provided by Jenkins or from the icons provided by this plugin. Some of the names of groovy-postbuild icons conflict with the names of Jenkins icons (e.g. yellow.gif). For these icons, you have to provide the complete path (e.g. /images/16x16/yellow.gif), in case you want a badge with the Jenkins icon. You can also use icons provided by other plugins (e.g. Green Balls), by specifying the complete path to the icon.

manager.addBadge("star-gold.gif", "icon from Jenkins")
manager.addBadge("yellow.gif", "icon from groovy-postbuild plugin")
manager.addBadge("/images/16x16/yellow.gif", "icon from Jenkins")
manager.addBadge("/plugin/greenballs/16x16/green.gif", "icon from greenballs plugin")

Example 6

The script below displays on the build summary page all classes that use Sun proprietary API.

pattern = ~/.*src\/main\/java\/(.*)\.java:[^ ]* (.*) is Sun proprietary API and may be removed in a future release.*/
def map = [:] { line ->
    matcher = pattern.matcher(line)
    if(matcher.matches()) {
        ownClass ="/", ".")
        sunClass =
        map[ownClass] = sunClass
if(map.size() > 0) {
    def summary = manager.createSummary("warning.gif")
    summary.appendText("Classes using Sun proprietary API:<ul>", false)
    map.each {
        summary.appendText("<li><b>$it.key</b> - uses $it.value</li>", false)
    summary.appendText("</ul>", false)

Example 7

The script below removes all badges and summaries from previous builds.

currentBuildNumber =
for(i=1; i<currentBuildNumber; i++) {
    if(manager.setBuildNumber(i)) {

Example 8

The script below marks the running build as deployed and the previous build as undeployed.

manager.createSummary("gear2.gif").appendText("<h2>Successfully deployed</h2>", false)

currentBuildNumber =
if(manager.setBuildNumber(currentBuildNumber - 1)) {
   actions =
    actions.each { action ->
        if (action.metaClass.hasProperty(action, "text") && action.text.contains("deployed")) {
    currDate = new Date().dateTimeString
    manager.addShortText("undeployed: $currDate", "grey", "white", "0px", "white")
    manager.createSummary("gear2.gif").appendText("<h2>Undeployed: $currDate</h2>", false, false, false, "grey")

Example 9 (thanks to Ken Bertelson)

The script below changes the description of the first failed test.

def tr =
def cr = tr.failedTests.get(0)
cr.description = "My CaseResult desc"

Example 10 (thanks to Frank Merrow)

Trivial, but hard to find the first time: Write a line to the job's Console Output:

manager.listener.logger.println("I want to see this line in my job's output");


To report a bug or request an enhancement to this plugin please create a ticket in JIRA (you need to login or to sign up for an account). Also have a look on How to report an issue

Key T P Summary


Version 2.3.1 (Feb 7, 2016)

  • Dependency to pipeline (aka. workflow) is optional (JENKINS-32589).

Version 2.3 (Dec 27, 2015)

  • Now built for Jenkins-1.609 and later
  • Supports workflow (JENKINS-26918)
    • You can use manager in workflow scripts.

Version 2.2.2 (Oct 17, 2015)

Version 2.2.1 (Aug 18, 2015)

Version 2.2 (Dec 19, 2014)

Version 2.1 (Oct 25, 2014)

Version 2.0 (Sep 21, 2014)

Version 1.10 (July 26, 2014)

  • added envVars and getEnvVariable(key)

Version 1.9 (April 29, 2014)

  • JENKINS-21924 Support run for matrix parent
  • change log level for each search from info to fine

Version 1.8 (August 22, 2012)

  • JENKINS-13024 Error in log indicating a missing descriptor
  • added clickable badge
  • Changed required Jenkins version to 1.466

Version 1.7 (May 2, 2012)

Version 1.6

Can use now additional classpath for groovy postbuild scripts to have them in a central location. Scriptler Plugin?

Version 1.5 (November 5, 2011)

  • Remove a html tag from the config page which causes an error on IE 7 (JENKINS-10079)



  1. Not seeing a component set up in JIRA for this plugin, and I'm reluctant to open an issue without assigning a component. Any chance the plugin author is subscribed to this page?

    The issue I'm having has to do with the images provided with the plugin. I'm getting broken image icons when adding a badge to a build.


    1. Unknown User (

      The groovy-postbuild component is now available in JIRA.

      1. Awesome, thanks! Still seeing broken images for images specific to this plugin. I'll log a bug shortly.

  2. I think having a way to remove or edit badges and summaries would be awesome. The only real way I can see to do this is to edit the config files directly. Even just providing some public methods that we can call through the groovy console (or the postbuild plugin itself) would be nice (wink)

    1. Unknown User (

      I have released a new version of this plugin (1.3), which offers support for adding and removing badges or summaries of previous builds. See examples 7 and 8.

  3. This plugin is great.

    I wondered how I could ever programmatically edit the descriptions for failed testcases without writing a plugin.  But with this plugin installed, it's basically just a few lines of code...something like this:

    def tr =
    def cr = tr.getFailedTests().get(0)
    cr.setDescription("My CaseResult desc")

    1. Unknown User (

      Great tip, thank you! It's now available as "Example 9".

  4. Is there a way to use the same groovy script within multiple jobs without having to cut-and-paste it each time?
    I got a groovy postbuild script running, then I copied its contents verbatim to a file on Hudson master.  Then, I tried this from Groovy Postbuild: File("/var/lib/hudson/userContent/postbuild-plugin.groovy").text);
    But got this:
        ERROR: Failed to evaluate groovy script.
        groovy.lang.MissingPropertyException: No such property: manager for class: Script1
    I tried a few things, but I couldn't get the embedded script to recognize my calls to the manager class.

    1. So after looking at source code plus trial and error, here's my solution:

      Binding binding = new Binding();
      binding.setVariable("manager", manager);
      GroovyShell shell = new GroovyShell(binding);
      shell.evaluate(new File("/var/lib/hudson/userContent/postbuild-plugin.groovy").text);

      1. Unknown User (

        Actually, you don't need to create a new GroovyShell. Instead, you can directly call the evaluate() method:

        evaluate(new File("/var/lib/hudson/userContent/postbuild-plugin.groovy"))

        Or, you can put your groovy script under SCM and specify a path relative to the workspace:

        evaluate(new File( + "/postbuild-plugin.groovy"))
        1. Just a word of warning there!
          The post build plugin runs on the manager and doing it as you say will fail if you are working with slaves!

          As I found out with my windows manager and mixed windows/linux/solaris slave setup :-(

          The best option is to define an extra env parameter in your runtime environment.

          Read: in the environment for the user as which you run hudson, e.g. your start script

          then you can do something link this

          def env = System.getenv();
          evaluate(new File(env['HUDSON_SCRIPT_DIR']+"/groovy/postbuild-ci.groovy").text);
          1. I've switched over to your better way of doing this.  Thanks to the both of you for your suggestions.

          2. Unknown User (masin_p)


            I found yours post and it interest me.I like to set new runtime variable in one project and then us this variable in other (buildis parametrized, but not trigered by first one). How to do it by groovy script (or in diferent way)? I was trying to do that like you wrote, but I'm new user of Hudson and groovy scripts and I have some problems with that.

          3. I really wanted to store the groovy script in the builds SCM so I use this script to copy the file to the master from the slave before executing it. Not pretty but it works.

            import hudson.FilePath;
            manager.listener.logger.println("About To Copy Groovy Postbuild script");
            projectWorkspaceOnMaster = new FilePath(new File(, "workspace"));
  "jenkins/groovyscripts/*.groovy", "", projectWorkspaceOnMaster);
            manager.listener.logger.println("About To Run Groovy Postbuild script");
            evaluate(new File( + "/workspace/jenkins/groovyscripts/postbuild.groovy"));
            manager.listener.logger.println("Finished Groovy Postbuild script");
  5. This might seem a basic question - but how do you query the object to determine the whether the build was successful or not? Is there a reference page to these various objects to see the methods available?

    1. Unknown User (

      You can use the following code:

      if( == hudson.model.Result.SUCCESS)

      See also Example 3.

      The variables available in your groovy scripts have the following java types:

      See the javadoc or have a look at the Hudson source code to learn how to use them.

  6. I love this plugin. Here's another thing that you can do...

    How to set the badge for the "Parent" Build of a Multi-configuration Project:

    import hudson.matrix.MatrixRun;
    import hudson.matrix.MatrixBuild;
    MatrixRun matrixRun =
    // Create logic to avoid setting the badge repeatedly.
    // I have a User-defined Axis named "RUN".  For my matrix,
    // only one child job runs when RUN=fmodel
    if (matrixRun.buildVariables.get("RUN") == "fmodel") {
        MatrixBuild matrixBuild = matrixRun.parentBuild
        manager.addShortText("hi","grey", "white", "0px", "white");
    1. If you want to have a more generic code you can use the following:

      manager.addShortText('Hello World')
      // FOR MATRIX BUILDS ONLY!!!!!!!!!!!!!!!!
      // lines above are for axises - for parent we have to clear the badgets and add it after
      // this prevents an comment for each axis on matrix-parent-build
      manager.addShortText('Hello World')
  7. Unknown User (alvescarlos)

    Excellent plugin!

    How can I read a user defined property of my Ant build file inside the Groovy Script?


    1. Unknown User (

      You can echo the value of your user-defined property and then grep for it in the log file.

      Put in your ant script something like:


      Put in your groovy script something like:

      def matcher = manager.getLogMatcher("^.*myProp=(.*)\$")
      if(matcher?.matches()) {
          def myProp =
          manager.addShortText(myProp, "grey", "white", "0px", "white")
      1. Unknown User (alvescarlos)

        Nice workaround! Works great.


  8. Unknown User (


    Using this priority plugin, I'd like to change the priority of the job based on whether or not the most recent build passed or failed. Any suggestions on how I could achieve this or if it is even possible?


    1. Unknown User (

      This is rather a hack, but it will probably do the job:

      def properties =
      def it = properties.values().iterator()
      while(it.hasNext()) {
          property =
          if( == "hudson.queueSorter.PrioritySorterJobProperty") {
              def priority = property.priority
              def result =
              if(result == hudson.model.Result.SUCCESS) priority += 10
              if(result == hudson.model.Result.FAILURE) priority -= 10
              def ctor = property.class.constructors[0]
              def newPrioProperty = ctor.newInstance(priority)
  9. Unknown User (breskeby)

    I'm using the pmd and the report violoations post build action to trace it. Now it would be nice to add a batch if the number of pmd violations has increased during this build. Is there a way to get these informations from the build model?


  10. Unknown User (breskeby)

    I'm using the pmd and the report violoations post build action to trace it. Now it would be nice to add a batch if the number of pmd violations has increased during this build. Is there a way to get these informations from the build model?


    1. Unknown User (

      You can use the following code to retrieve the number of pmd violations:

      def pmdViolations = 0 { action ->
          if(action.class.simpleName == "ViolationsBuildAction") {
              pmdViolations ="pmd") ?: 0
      manager.addShortText("$pmdViolations pmd violations", "grey", "white", "0px", "white")

      The above code works only if GroovyPostbuild runs after the Violations plugin. One way to ensure this is to edit the config.xml of your project and to place the <org.jvnet.hudson.plugins.groovypostbuild.GroovyPostbuildRecorder> element after the <hudson.plugins.violations.ViolationsPublisher> element. Then, restart Hudson. The annoying thing is that the order of publishers is reset when saving the configuration, so you will have to repeat these operations each time you make a change to the project configuration.

      To avoid these annoyances, you could build a custom version of GroovyPostbuild that will always run after the Violations plugin. In order to this, you have to retrieve the source code of GroovyPostbuild and adjust the annotation of GroovyPostbuildDescriptor: @Extension(ordinal=-1).

  11. Just for the record - how would I generate some log statements?


    does not produce any output.

    1. println writes to the jenkins log. You should use


      to write log statements to the build log.

  12. ERROR: Failed to evaluate groovy script. /etc/init.d/pom.xml (No such file or directory)
    at Method)
    Finished: SUCCESS

    Uh? Am I the only one expecting here a build error?

    1. In version 1.4, which I released today, you can choose the desired behavior in case of a script failure. Give it a try!

  13. Example 4 didn't work for me but this does:

    def matcher = manager.getMatcher(, ".*Total time: (.*)\$")
    if(matcher.matches()) {
        manager.addShortText(, "grey", "white", "0px", "white")
    1. I guess, my regex worked only for ant builds. I changed example 4 to use your regex and getLogMatcher instead of getMatcher.

      1. Both examples don't work for me. The one written in documentation just doesn't do anything, the one given by Neil fails with:Cannot invoke method matches() on null object

  14. This plugin is a great work, thanks !
    However, the trouble below has occurred in our Jenkins since I wrote a experimental job using this plugin.

    When someone tries to open any job-config page of any job in IE8, IE8 raises a javascript error.
    I posted a report to JIRA,  JENKINS-10079.


  15. I wonder How I can upgrade the status in the upstream from the downstream jobs using this plugin. I've googled and found the next link: [], but I didn't run. Any clue?

    For instance:


     |                                           |
    Job_Build                     Job_StaticTesting

    Job_Dispatcher and Job_Notifcation should be updated to "unstable" or similar status whenever the Job_Build or Job_StaticTesting fail.

    Thanks in advance.

    1. I was looking to do basically the same thing, except when an job starts I want all it's downstream jobs marked as something like unstable.  So if you find a solution, please post it back here.

  16. I am trying to mark a build as UNSTABLE when it fails

    if ( == hudson.model.Result.FAILURE) {

    but it remains marked as a failure and in the console out I even see the following line

    Build step 'Groovy Postbuild' marked build as failure

    even if I don't do that in the Groovy Postbuild. Somehow it's enough for the build to fail in order for this line to appear. That's weird.

    Is there anyway to mark a failed build as unstable?

  17. Is it possible to make Groovy Postbuild run as the very last of the post-build actions? Currently JUnit publisher runs after the Groovy Postbuild.

    1. I doubt if that's possible.

      There is an open ticket in the Jenkins and Hudson issue tracker to add a way to specify the post build actions executions:

      from this page.

  18. Hi I've written the following lines a part of my Groovy postbuild code:

    if (buildList[0].getResult().isBetterThan(buildList[i].getResult())){buildList[0].setResult(buildList[i].getResult());

    if (buildList[0].getResult().isBetterThan(buildList[i].getResult())){buildList[0].setResult(buildList[i].getResult());

    This will set the result of the build in buildList[0] to the status of buildList[i] if buildList[0] status is better that buildList[i].

    The logic works and sets the build status as it should. But the status is not "persisting" i.e once I restart the Jenkins service the status of the buildList[0] is reverted to its original status.

    How can I make this change permanent?

    1. I figured it out myself. All I had to do was add the line:

  19. This plugin looks like the best candidate for dynamically triggering downstream parameterized builds. (See my Stack Overflow question.) Anybody know how?

  20. What's the best way to write to a file in the workspace of the slave?

    I can't seem to figure out how to create a properties file in the workspace that gets written to the slave and not the master :(

  21. Is there a way to get the fact that there are Badges indicated on the main Jenkins page "All" or in one of the "View Tabs"?

    Nice to have the Badge at the Build Level, but I'd like to see those indications (or at least that there ARE Badge regardless of what they actually are) at the main view page?

    Is that possible?


  22. Hi!

    that's a nice plugin! but I ask if is possible to customize the behavior associated to the icon in the build list; so instead of opening a popup, going directly to a link for example.

    I know that a solution is to add a short text with link, but I think it's much better to click the icon and go =)

    Is it also possible to add custom icons?


  23. Hi! I'm trying to display high-priority warnings from the Warnings Plugin on the build summary page. Here is what I came up with:

    if ( == hudson.model.Result.FAILURE) {
        def warningsResultAction = { it.class.simpleName == "WarningsResultAction" }
        if (warningsResultAction) {
            def newWarnings = warningsResultAction.result.newWarnings
            if (newWarnings.size() > 0) {
                def summary = manager.createSummary("error.gif")
                summary.appendText("<p><b>Build errors:</b></p><ul>", false)
                newWarnings.each {
                    if (it.priority.toString() == "HIGH") {
                        summary.appendText("<li>In <b>${it.fileName}</b> at line ${it.primaryLineNumber}: ${it.message}</li>", false, false, false, "#A33")
                summary.appendText("</ul>", false)

    Basically, this code works, but I don't like the following comparison:

    it.priority.toString() == "HIGH"

    How can I make it more elegant? Importing hudson.plugins.analysis.util.model.Priority results in "unable to resolve class hudson.plugins.analysis.util.model.Priority". Is it possible to use this enum?
    P.S. I'm relatively new to Java/Groovy.

  24. Note:  I don't want to use the promotion plugin because it will only notify on passing builds.

    I have the following build pipeline.

    Job A -> Job B -> Job C -> System Test

    Any of these jobs trigger the build pipeline to start depending on the code change.  (I use Mercurial with the modules option.)  Also Job B uses artifacts from the last successful Job A, Job C uses artifacts from Job B, and the system test uses artifacts from all jobs.

    I want to be able to mark all upstream jobs as bad if any part of the build pipeline fails.  I have figured out how to do that, but I also want to mark them as good when the full succeeds.  Currently you can't improve the build status of a build with any API I have found.  I thought it might be useful to add a badge to the upstream builds instead and remove them after the build is good again.  I have a arrray of all of the upstream builds.  Does anyone know how to add a badge to a different build?

    1. I figured it out.  I just had to use manager.setBuild().

  25. Hi,

    Is there a way to use this plugin to check whether a specific artifact has been created and it's present in the workspace and otherwise set the buildstatus to failed ? if this is not the most indicated plugin can anyone please point me to the right method ? thanks.

  26. Can someone provide an example of working with a centralized script that contains functions I can call from various jobs?  I can't seem to define my .groovy code correctly to get it to work.

    If I wanted to convert Example 8 from above so that it lives in a file at "C:/myfolder" that I can reference via the "Additional groovy classpath", how might that utility script look, and what might a call to the function look?

    Thanks in advance 

    1. Nevermind.  Figured it out.  In case anyone is interested.

      I created a script at "C:\myfolder\Example8.groovy" that looks like this:

      class Example8 {
          static def run(manager) {
              manager.createSummary("gear2.gif").appendText("<h2>Successfully deployed</h2>", false)
              def currentBuildNumber =
              if(manager.setBuildNumber(currentBuildNumber - 1)) {
                  def actions =
                  actions.each { action ->
                      if (action.metaClass.hasProperty(action, "text") && action.text.contains("deployed")) {
                  def currDate = new Date().dateTimeString
                  manager.addShortText("undeployed: $currDate", "grey", "white", "0px", "white")
                  manager.createSummary("gear2.gif").appendText("<h2>Undeployed: $currDate</h2>", false, false, false, "grey")

      Set the "Additional groovy classpath" to "C:/myfolder", and call it in "Groovy script" that looks like this:
  27. I have a general purpose Groovy script that does some postbuild actions that I want to use on multiple jobs, I've tried using the additional groovy classpath to call the script but that doesn't work. How do I use that feature properly?

  28. I have been using this plugin for a while, it is great. But I am wondering if there is a way to get this same functionality either pre-build or during the build step. 

    The functionality I am looking for is a way to modify the note next to each build. What is here the addShortText() function.

    I have not found any way to modify this or recreate this functionality outside of this plugin, any help would be greatly appreciated.

    Also - on the same note, why do you not make the same plugin available at other stages of the build as well?

    1. Seems like in your main process you could leave yourself a "file" or artifact of some kind and have the post build plugin actually post the short text for you . . . just later.

      Of course if you want some dynamic short text that changes as your job runs . . . that isn't as useful.

      Part of the problem here is that the post build plugin runs inside the Jenkins JVM and so can get its hand on Jenkins internals . . . where as the build steps are forked and run in their own process space . . . so then don't have access to Jenkins internals at all.

  29. Hi,

    I am interested in doing the following:

    • Analyse the console log and identify known errors/points of interest [I have this working]
    • Make a list of the errors on the summary for a given build [I found the example so should be easy]
    • Make a hyperlink from each error to the corresponding place in the console output [I basically need to add HTML anchors to the relevant lines of the logs but how can I do this?]

    I looked into the ConsoleNote or ConsoleAnnotator interfaces, but I am unsure how to utilize these from the plugin? Can anybody give me a hint? :)


  30. Hi,

    in a PHP-Project generating a Clover Coverage-Report,  I'm trying to figure out a way to access and parse the clover.xml file, which is generated by phpunit, using a Groovy Postbuild script...

    Is there a way to access and parse the file in the most recent build and previous builds and if so, which methods can be used to achieve this.

    Thanks for any hints...


  31. Jenkins: 1:523, PostBuild: 1.8

    I have a Groovy script . . . that will eventually be a post build script . . . for now the script runs on its own and connects to a Database, but with this CLASSPATH set:

    SET CLASSPATH=C:\Users\fmerrow\Downloads\Microsoft JDBC Driver 4.0 for SQL Server\sqljdbc_4.0\enu\sqljdbc4.jar

    However, when I try to get the working script to run as a post build . . . I cannot find the class in that file.

    I've tried specify as Directory using "Additional groovy classpath" and when that didn't work as full path to the Jar file.  I also wondered if spaces would be an issue . . . Quoting gave odd results (pretended C:\Program Files(x85)\Jenkins to the path) so I moved it into a directory with no spaces and again tried both file and directory . . . I cannot seem to get it to find the class in this jar file.



  32. Is there any way to test a script written for the plugin without running a full build?

    I'm trying to write a plugin to run at the end of a 90 minute build, and don't especially want to trigger a full build each time I want to debug my groovy script.. It would be great if I could re-run the plugin on a previous build - for example via a URL like the ones provided to remove badges.

    (In the meantime I'm planning on creating a fake build which just dumps the output from an old build to the right places, but it's a bit of a hassle..)



    Edit: Better option - used the nodestalker plugin to create a new build which shares the same workspace as my 90 minute one, and has no build actions apart from running the groovy postbuild script

  33. I'm trying to add short text to a promoted build.  I'm using the Promoted Builds Plugin and adding an action to run a Groovy Postbuild script.  I think because of the way the promoted build runs its actions as some sort of sub project, the object is wrong.  After reading these comments, I thought I could use the manager.setBuild() method (which I don't see documented anywhere), but I'm having no luck.  Here's what I tried.

    project = manager.hudson.getJob(${PROMOTED_JOB_NAME})
    build = project.getBuildByNumber(${PROMOTED_NUMBER})

    where buildLabel is the parameter defined in the promotion process.

    This is what I get:

    Started by user build
    Building on master in workspace /extraspace/jenkins/jobs/Test/workspace
    Promoting Test #28
    \[workspace\] $ /bin/sh \-xe /tmp/
    + /bin/echo Promoted build 28 as 1.2.4
    Promoted build 28 as 1.2.4
    build hudson.tasks.Shell@4071cd14 SUCCESS
    ERROR: Failed to evaluate groovy script.
    groovy.lang.MissingMethodException: No signature of method: Script1.$() is applicable for argument types: (Script1$_run_closure1) values: \[Script1$_run_closure1@69c60ffb\]
    Possible solutions: is(java.lang.Object), run(), run(), any(), use(\[Ljava.lang.Object\;), any(groovy.lang.Closure)
     at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(
     at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(
     at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(
     at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(
     at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(
     at groovy.lang.GroovyShell.evaluate(
     at groovy.lang.GroovyShell.evaluate(
     at groovy.lang.GroovyShell.evaluate(
     at org.jvnet.hudson.plugins.groovypostbuild.GroovyPostbuildRecorder.perform(
     at hudson.plugins.promoted_builds.Promotion$
     at hudson.plugins.promoted_builds.Promotion$RunnerImpl.doRun(
     at hudson.model.AbstractBuild$
     at hudson.model.Run.execute(
     at hudson.model.ResourceController.execute(
    build org.jvnet.hudson.plugins.groovypostbuild.GroovyPostbuildRecorder@3506ec4f SUCCESS
    Finished: SUCCESS
    1. If anyone is interested, I got this to work by accessing the build environment variables instead of using token replacement ${} notation. Maybe there's a better way, but I'm no Groovy expert.

      def thr = Thread.currentThread()
      def build = thr.executable
      def envVars = build.envVars
      def promotedJob = envVars?.PROMOTED_JOB_NAME
      def promotedNumber = envVars?.PROMOTED_NUMBER.toInteger()
      def buildLabel = envVars?.buildLabel
      project = manager.hudson.getJob(promotedJob)
      build = project.getBuildByNumber(promotedNumber)

      Now if I could get rid of the star, I could just use this label to indicate it was promoted...

  34. Hello all,

    How can I insert a summary (with icon) into specific index (say before or after some another summary)?

    I noticed that this plugin can only append summary or badges to the end of the list. How can I insert info after (or before) existing summary/badge programmatically?

    And also how can I update an existing summary (example: add committers usernames to SCM changes list)?

  35. update test result in jira from jenkins:

    import groovy.json.JsonSlurper
    def authorization = "Authorization: Basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    def contentType = "Content-Type: application/json"
    def acceptEncoding = "Accept-Encoding: gzip,deflate"
    def url = ""
    def suites =
    //select all tests by component (=TestSuite)
    def searchBody = new groovy.json.JsonBuilder()
      jql "project = TEST AND type = Test AND component = test"
      startAt "0"
      maxResults "300"
      fields (["id","key","summary","status"])
    def proc = ["curl", "-X", "POST", "-H",  authorization,"-H", contentType , "-H", acceptEncoding, url+"search", "-d", searchBody.toString()].execute()
    def out = new StringBuilder()
    def err = new StringBuilder()
    proc.waitForProcessOutput(out, err)
    if (out) manager.listener.logger.println "out:\n$out"
    if (err) manager.listener.logger.println "err:\n$err"
    jiraTests = new JsonSlurper().parseText(out.toString())
    manager.listener.logger.println  "total: " + + "jiraTests: " + jiraTests.maxResults
    def  builderFailedToOpen = new groovy.json.JsonBuilder()
         builderFailedToOpen.transition{id "711"}
    def  builderPassedToOpen = new groovy.json.JsonBuilder()
         builderPassedToOpen.transition{id "721"}
    def  builderClosedToOpen = new groovy.json.JsonBuilder()
         builderClosedToOpen.transition{id "3"}
    def  builderBlockedToOpen = new groovy.json.JsonBuilder()
         builderBlockedToOpen.transition{id "821"}
    //set all test to Open
        case "Test passed":
          proc = ["curl", "-X", "POST", "-H",  authorization,"-H", contentType ,it.self +"/transitions", "-d", builderPassedToOpen.toString()].execute()
          manager.listener.logger.println proc.text
        case "Test failed":
          proc = ["curl", "-X", "POST", "-H",  authorization,"-H", contentType ,it.self +"/transitions", "-d", builderFailedToOpen.toString()].execute()
          manager.listener.logger.println proc.text
        case "Test Blocked":
          proc = ["curl", "-X", "POST", "-H",  authorization,"-H", contentType ,it.self +"/transitions", "-d", builderBlockedToOpen.toString()].execute()
          manager.listener.logger.println proc.text
        case "Closed":
          proc = ["curl", "-X", "POST", "-H",  authorization,"-H", contentType ,it.self +"/transitions", "-d", builderClosedToOpen.toString()].execute()
          manager.listener.logger.println proc.text
    def  builderOpenToPassed = new groovy.json.JsonBuilder()
         builderOpenToPassed.transition{id "741"}
    def  builderOpenToFailed = new groovy.json.JsonBuilder()
         builderOpenToFailed.transition{id "731"}
    def updatedTestCount = 0
      manager.listener.logger.println it.getName()
          manager.listener.logger.println  it.getDisplayName() + " :" + it.isPassed()
          displayName = it.getDisplayName()
          testMatch  = jiraTests.issues.findAll(){it.fields.summary.toString() == displayName}
          manager.listener.logger.println "testMatch: " + testMatch.key + " " + testMatch.self
          switch (testMatch.size()){
             case 1:
                manager.listener.logger.println testMatch.self[0]
                if (it.isPassed()){
                  proc = ["curl", "-X", "POST", "-H",  authorization,"-H", contentType ,testMatch.self[0] +"/transitions", "-d", builderOpenToPassed.toString()].execute()
                } else {
                  proc = ["curl", "-X", "POST", "-H",  authorization,"-H", contentType ,testMatch.self[0] +"/transitions", "-d", builderOpenToFailed.toString()].execute()
                manager.listener.logger.println proc.text
                manager.listener.logger.println  "Test found: " + it.getDisplayName()
             case 0:
                manager.listener.logger.println  "Test not found: " + it.getDisplayName()
                manager.listener.logger.println "Too much matches: " + it.getDisplayName()
    if ( > updatedTestCount){
      manager.listener.logger.println "WARNING: Jira total($ is more than updated test quantity ($updatedTestCount)"
  36. How to send email from Groovy Post Build , basically i have requirement that based on different conditions send email to different groups.

    Some thing like 

    if(manager.logContains("CHECK LOG 1 "))

    Unknown macro: { //Send email to Group -1 }

    else if if(manager.logContains("CHECK LOG 2 ")) {

    //Send email to Group -2

    Is there some thing inbuild in plugin or groovy that can be used to send email ?
    Or any better solution 

  37. Is it possible to add an item to the project summary page rather than the build summary page?

    Ideally I would also like to add a item in the list of links on the left side of the page as well.  Just not sure if I would need to wirte a plugin to do this or if its possible to do it with this plugin.

  38. Hey there everyone,

    Small question - using the MultiJobBuild.getSubBuilds() method, you can get a list of jobs directly under the MultiJobBuild you called it on. The SubBuilds, however, don't have their own getSubBuilds() method. Is there any way I could gain access to the builds which are the subbuilds of each of those SubBuilds returned by MultiJobBuild.getSubBuilds()?

  39. Is there any way to call buildUnstable with a job name?  I want to create a job that can mark any build as unstable using a parameter for the build name.

    thank you.

  40. Hi guys!

    I have several builds which are using the same post groovy script.

    Is there a way to get templates for a postbuild groovy scripts? For example to reuse groovy templates defined in Managed Script Plugin (or some alternative)?

    thank you in advance!

  41. r G

    Hi guys!

    I've been using this awesome plugin for a few years now but since the "whitelisted operation feature" was released/installed into our current Jenkins instance by our DEV ops team (I have to run my scripts under the "sandbox" ), I'm just getting headaches. Specifically, it's been now a couple of times that our DEV ops has installed some kind of "Jenkins security plugin" and as a result ALL the operations that were already whitelisted are NO longer valid and they have to be "re-approved" (at least that's what I've been told... ). In fact that last "piece of approval" is what it's giving me plenty of headaches since I've been told that in order to whitelist all the required method for my scripts I have to operate on this kind of "extremely time consuming" loop:

    1) run the script
    2) crash on the invalid operation
    3) method needs to be approved by DEV ops team
    GOTO 1) until script runs fine

    As you can imagine, this is an extremely painful and slow process since a statement as simple as manager.listener.logger.println("Hi world" ) may require several iterations on the previous loop.

    Is anyone aware of any faster way to speed up this "loop" ? something such as providing my DEV ops team with a list of methods: manager.listener.logger.println(), method2() .... , which they can "copy/paste into that whitelist file"?

    Any feedback on this is more than welcome.

    Thank you guys in advance for your time!


  42. Hello,

    I am adding the plugin to my upstream build to determine if any of the downstream builds failed and put this info into summary. Is there a way to do that?  returns an empty collection even though I have a few downstream projects (invoked with parameterized triggers), and - not sure if this is what i need. Any suggestions are greatly appreciated.

Write a comment…