Skip to content

Instantly share code, notes, and snippets.

@jaysoncena
Created April 18, 2016 09:25
Show Gist options
  • Save jaysoncena/4b18951c3c5e68a9049ad340878761e9 to your computer and use it in GitHub Desktop.
Save jaysoncena/4b18951c3c5e68a9049ad340878761e9 to your computer and use it in GitHub Desktop.
Jenkins - Get the user who triggered the current or the parent job
def triggeredBy = "---"
def iterateCause(b) {
upstreamcause = b.getCause(hudson.model.Cause.UpstreamCause.class)
if (upstreamcause != null) {
job = Jenkins.getInstance().getItemByFullName(upstreamcause.getUpstreamProject(), hudson.model.Job.class)
if (job != null) {
upstream = job.getBuildByNumber(upstreamcause.getUpstreamBuild())
if (upstream != null) {
iterateBuild(upstream)
}
}
}
usercause = b.getCause(hudson.model.Cause.UserIdCause.class)
if (usercause != null) {
triggeredBy = usercause.getUserName()
}
return;
}
iterateCause(build)
@vanderboon
Copy link

thanks!

@capitalterefe
Copy link

capitalterefe commented Dec 10, 2021

if you just need the build-number or just the upstream project name, you can use something like.
def upstream_project = "${currentBuild.getBuildCauses()[0].upstreamProject}"
echo "Build Caused by ${upstream_project}"

@elouanKeryell-Even
Copy link

I wasn't authorized to use the rawBuild method, so I did it like this:

pipeline {
    agent any
    stages {
        stage('Print user') {
            steps {
                script {
                  if(currentBuild.upstreamBuilds){
                    print("Parent")
                    print(currentBuild.upstreamBuilds[0].getBuildCauses()[0].userId)
                  } else {
                    print("No parent")
                    print(currentBuild.getBuildCauses()[0].userId)
                  }
                }
            }
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment