How to distinguish assembly triggers in a Jenkins pipeline

I hope to add a conditional step to my Jenkinsfile, which starts depending on how the assembly was created. We are currently configured so that assemblies are either started using:

  • changes to our git repository, which is selected when indexing branches
  • the user manually starts the build using the 'build now' button in the user interface.

Is there a way to start different transition steps, depending on which of these actions caused the assembly?

+12
source share
5 answers

The following code should work to determine if the user has started a pipeline or timer / other trigger:

def isStartedByUser = currentBuild.rawBuild.getCause(hudson.model.Cause$UserIdCause) != null
+10

2.22 (2018 02) API . JENKINS-41272.

currentBuild currentBuild :

getBuildCauses

  • JSON-

- getBuildCauses(String causeClass)

  • , Cause JSON- , , JSON-, .

, :

echo "${currentBuild.buildCauses}" // same as currentBuild.getBuildCauses()
echo "${currentBuild.getBuildCauses('hudson.model.Cause$UserCause')}"
echo "${currentBuild.getBuildCauses('hudson.triggers.TimerTrigger$TimerTriggerCause')}"

:

[Pipeline] echo
[[_class:hudson.model.Cause$UserIdCause, shortDescription:Started by user anonymous, userId:null, userName:anonymous], [_class:org.jenkinsci.plugins.workflow.cps.replay.ReplayCause, shortDescription:Replayed #12]]
[Pipeline] echo
[]
[Pipeline] echo
[]
[Pipeline] End of Pipeline
Finished: SUCCESS

, currentBuild.getBuildCauses(type) type Cause . , currentBuild.getBuildCauses('org.jenkinsci.plugins.workflow.cps.replay.ReplayCause') java.lang.ClassNotFoundException. JENKINS-54673 2.22 Pipeline: Supports APIs (workflow-support). , 2.24.

+2

, . , :

import com.cloudbees.groovy.cps.NonCPS

@NonCPS
def isStartedByTimer() {
    def buildCauses = currentBuild.rawBuild.getCauses()
    echo buildCauses

    boolean isStartedByTimer = false
    for (buildCause in buildCauses) {
        if ("${buildCause}".contains("hudson.triggers.TimerTrigger\$TimerTriggerCause")) {
            isStartedByTimer = true
        }
    }

    echo isStartedByTimer
    return isStartedByTimer

}

// [...]
// Other pipeline stuff

script {
    isStartedByTimer()
}

:

00:00:01.353 [hudson.model.Cause$UserIdCause@fa5cb22a]
[Pipeline] echo
00:00:01.358 false

:

00:00:01.585 [hudson.triggers.TimerTrigger$TimerTriggerCause@5]
[Pipeline] echo
00:00:01.590 true

: NonCPS , , .

+2

"BUILD_CAUSE" ,

[jenkins-pipe]

currentBuild.rawBuild.getCauses()

(. github.com/jenkinsci/pipeline-examples/blob/master/... )

+1

Jenkins Pipeline currentBuild.rawBuild :

// started by commit
currentBuild.getBuildCauses('jenkins.branch.BranchEventCause')
// started by timer
currentBuild.getBuildCauses('hudson.triggers.TimerTrigger$TimerTriggerCause')
// started by user
currentBuild.getBuildCauses('hudson.model.Cause$UserIdCause')
0

Source: https://habr.com/ru/post/1675566/


All Articles