Skip to content

Instantly share code, notes, and snippets.

@SGTMcClain
Last active May 16, 2024 02:03
Show Gist options
  • Save SGTMcClain/15afb8a342910ccca4c24c3351fa1054 to your computer and use it in GitHub Desktop.
Save SGTMcClain/15afb8a342910ccca4c24c3351fa1054 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