How to differentiate build triggers in Jenkins Pipeline

后端 未结 7 1648
挽巷
挽巷 2020-12-03 10:23

I\'m hoping to add a conditional stage to my Jenkinsfile that runs depending on how the build was triggered. Currently we are set up such that builds are either triggered by

7条回答
  •  悲哀的现实
    2020-12-03 10:48

    I think that the answers here are incomplete and do not provide an actual ready to use answer. Here's my code to get it working:

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

    When started by user:

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

    When started by timer:

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

    Note: the NonCPS decorator is needed because otherwise the next non-script step will throw.

提交回复
热议问题