Don't understand german? Read or subscribe to my english-only feed.

Jenkins: marking an upstream job as failed if its downstream job fails

Since I’m not aware of a ready-to-go solution, this issue once again came up at a company where I’m doing Jenkins/CI consulting for and the solution involves some trickiness you need to be aware of I’m hereby documenting it.

If you have a build pipeline inside your Jenkins setup you might have so called upstream jobs which trigger downstream jobs. If such a downstream job fails you might want to set the build state of the upstream job to “failure” as well.

First of all install the Groovy Postbuild Plugin as well as the Copy Artifact Plugin. (The Copy Artifact Plugin is not strictly needed, you can also choose a different approach for artifact handling, but the plugin works very well for me.)

In the upstream job you have to archive artifacts. Otherwise the script that we will use in the downstream job doesn’t have a connection to the upstream job through the getUpstreamBuilds() method. If you don’t have any artifacts then just create a simple textfile and use that as artfifact file. After the artifact step you can place the trigger for the downstream job. This is the relevant part for a working sample configuration for such an upstream job:

Screenshot Jenkins upstream job configuration

In the downstream job make sure to grab the artifacts from the upstream job. Then use build steps or whatever you need as usual. This is the relevant part for a working sample configuration for such a downstream job:

Screenshot Jenkins downstream job configuration

Finally use the following Groovy script as the Groovy Postbuild action:

upstreamBuilds = manager.build.getUpstreamBuilds();

if(!upstreamBuilds) {
  manager.listener.logger.println("Error: could not identify upstream build");
} else {
  upstreamJob = upstreamBuilds.keySet().iterator().next();
  lastUpstreamBuild = upstreamJob.getLastBuild();
  buildResult = manager.build.result;

  if(lastUpstreamBuild.getResult().isBetterThan(buildResult)) {
    manager.listener.logger.println("Adjusting build state of upstream job to build result of this job, being " + buildResult);
    lastUpstreamBuild.setResult(buildResult);
  }
}

That’s it. Now every time your downstream job fails it should set the according upstream job to “failure” as well.

Comments are closed.