Skip to content

Instantly share code, notes, and snippets.

@staticor
Forked from SGTMcClain/Jenkinsfile
Created May 16, 2024 02:03
Show Gist options
  • Save staticor/1a6d0c14409dea3df70243bd208f9524 to your computer and use it in GitHub Desktop.
Save staticor/1a6d0c14409dea3df70243bd208f9524 to your computer and use it in GitHub Desktop.
Find Jenkins Build cause
#!/usr/bin/env groovy
import hudson.model.*
import hudson.EnvVars
import groovy.json.JsonSlurperClassic
import groovy.json.JsonBuilder
import groovy.json.JsonOutput
import java.net.URL
pipeline {
agent any
stages {
stage('Check Build Cause'){
steps{
script{
// get Build Causes
// https://stackoverflow.com/questions/43597803/how-to-differentiate-build-triggers-in-jenkins-pipeline
echo "${currentBuild.getBuildCauses()}" //Always returns full Cause
echo "${currentBuild.getBuildCauses('jenkins.branch.BranchEventCause')}" // Only returns for branch events
echo "${currentBuild.getBuildCauses('hudson.triggers.SCMTrigger$SCMTriggerCause')}" // Only returns SCM Trigger
echo "${currentBuild.getBuildCauses('hudson.model.Cause$UserIdCause')}" // Only returns if user initiates via Jenkins GUI
def GitPushCause = currentBuild.getBuildCauses('jenkins.branch.BranchEventCause')
def UserCause = currentBuild.getBuildCauses('hudson.model.Cause$UserIdCause')
// If a cause was populated do...
if (GitPushCause) {
println "********* Git Push *********"
println GitPushCause.getShortDescription()
stage ('Stage 1') {
sh 'echo Stage 1'
}
} else if (UserCause) {
println "******* Manual Build Detected *******"
println UserCause.getShortDescription()
stage ('Stage 2') {
sh 'echo Stage 2'
}
}else {
println "unknown cause"
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment