Jenkins声明性管道:找出触发工作

时间:2017-10-24 10:41:26

标签: jenkins jenkins-pipeline jenkins-2 jenkins-declarative-pipeline

我们有一个使用declarative pipeline的Jenkins工作。

此作业可以由不同的其他版本触发。

在声明性管道中,如何找出哪个构建触发了管道?

2 个答案:

答案 0 :(得分:4)

下面的代码示例

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

您可以查看作业的REST API以获取如下所示的额外信息

{
  "_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/"
        }
      ]
    },

参考:

答案 1 :(得分:0)

我意识到这已经有两年了,但是先前的响应需要在我的Jenkins实例中进行一些额外的安全设置。经过一些研究,我发现在11/2018中完成了一个新功能请求,该请求可以解决此需求并在currentBuild中公开构建原因。这是我写的一个小库,如果构建是由另一个构建触发的,则返回带有字符串“ JOB /”的原因:

def call(body) {
    if (body == null) {body = {DEBUG = false}}
    def myParams= [:]
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body.delegate = myParams
    body()

    def causes = currentBuild.getBuildCauses()
    if (myParams.DEBUG) { 
        echo "causes count: " + causes.size().toString()
        echo "causes text : " + causes.toString()
    }
    for(cause in causes) {
        // echo cause
        if (cause._class.toString().contains("UpstreamCause")) {
            return "JOB/" + cause.upstreamProject
        } else {
            return cause.toString()
        }
    }
}

要使用此功能,我将其放置在名为“ buildCause.groovy”的文件中的库中。然后,在我的Jenkinsfile顶部引用该库:

library identifier: 'lib@master', retriever: modernSCM(
        [$class: 'GitSCMSource', remote: '<LIBRARY_REPO_URL>',
         credentialsId: '<LIBRARY_REPO_CRED_ID', includes: '*'])

然后我可以根据需要在管道中调用它:

def cause=buildCause()
echo cause
if (!cause.contains('JOB/')) {
    echo "started by user"
} else {
    echo "triggered by job"
}