Jenkins declarative pipeline: find out triggering job

Bernhard picture Bernhard · Oct 24, 2017 · Viewed 7.2k times · Source

We have a Jenkins job that uses a declarative pipeline.

This job can be triggered by different other builds.

In the declarative pipeline how can I find out which build has triggered the pipeline?

Answer

Larry Cai picture Larry Cai · Oct 25, 2017

Code sample below

pipeline {
    agent any
    stages {
        stage('find upstream job') {
            steps {
                script {
                    def causes = currentBuild.rawBuild.getCauses()
                    for(cause in causes) {
                        if (cause.class.toString().contains("UpstreamCause")) {
                            println "This job was caused by job " + cause.upstreamProject
                        } else {
                            println "Root cause : " + cause.toString()
                        }
                    }
                }      
            }
        }
    }
}

You can check the job's REST API to get extra information like below

{
  "_class" : "org.jenkinsci.plugins.workflow.job.WorkflowRun",
  "actions" : [
    {
      "_class" : "hudson.model.ParametersAction",
      "parameters" : [

      ]
    },
    {
      "_class" : "hudson.model.CauseAction",
      "causes" : [
        {
          "_class" : "hudson.model.Cause$UpstreamCause",
          "shortDescription" : "Started by upstream project \"larrycai-sto-46908390\" build number 7",
          "upstreamBuild" : 7,
          "upstreamProject" : "larrycai-sto-46908390",
          "upstreamUrl" : "job/larrycai-sto-46908390/"
        }
      ]
    },

Reference: