Notifications on jenkins job failures - with pipeline from scm

Viewed 1499

We have several jenkins pipeline jobs setup as "pipeline from scm" that checkout a jenkins file from github and runs it. There is sufficient try/catch based error handling inside the jenkinsfile to trap error conditions and notify the right channels.This blog post goes into a quite a bit of depth about how to achieve this.

However, if there is issue fetching the jenkinsfile in the first place, the job fails silently. How does one generate notifications from general job launch failures before the pipeline is even started?

3 Answers

Jenkins SCM pipeline doesn't have any execution provision similar to catch/finally that will be called if Jenkinsfile load is failed, And I don't think there will be any in future.

However there is this global-post-script which runs groovy script after every build of every job on Jenkins. You have to place that script in $JENKINS_HOME/global-post-script/ directory.

Using this you can send notifications or email to admins based on project that failed and/or reason/exceptions of failure.

Sample code that you can put in script

if ("$BUILD_RESULT" != 'SUCCESS') {
  def job = hudson.model.Hudson.instance.getItem("$JOB_NAME")
  def build = job.getBuild("$BUILD_NUMBER")
  def exceptionsToHandle = ["java.io.FileNotFoundException","hudson.plugins.git.GitException"]
  def foundExection = build
    .getLog()
    .split('\n')
    .toList()
    .stream()
    .filter{ line -> 
      !line.trim().isEmpty() && !exceptionsToHandle.stream().filter{ex -> line.contains(ex)}.collect().isEmpty()
    }
    .collect()
    .size() > 0;
  println "do something with '$foundExection'"
}

Apparently this is an open issue with Jenkins: https://issues.jenkins.io/browse/JENKINS-57946

I have decided not to use Yogesh answer mentioned earlier. For me it is simpler to just copy the content of the Jenkinsfile directly into the Jenkins project instead of pointing Jenkins to the GIT location of the Jenkinsfile. However, in addition I keep the Jenkinsfile in GIT. But make sure to keep the GIT and the Jenkins version identical.

Related