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)
@pere3
Copy link

pere3 commented Aug 26, 2020

Thanks for a snippet, it put me in a right way with upstream causes.
In 2020 and Jenkins 2.235.2 i've done it working with this:

def getBuildUser(currentBuild=currentBuild) {
  def userCause = currentBuild.rawBuild.getCause(Cause.UserIdCause)
  def upstreamCause = currentBuild.rawBuild.getCause(Cause.UpstreamCause)

  println("User cause: " + userCause)
  println("Upstream cause: " + upstreamCause)

  if (userCause) {
    userCause.getUserId()
  } else if (upstreamCause) {
    def upstreamJob = Jenkins.getInstance().getItemByFullName(upstreamCause.getUpstreamProject(), hudson.model.Job.class)
    if (upstreamJob) {
      def upstreamBuild = upstreamJob.getBuildByNumber(upstreamCause.getUpstreamBuild())
      if (upstreamBuild) {
        def realUpstreamCause = upstreamBuild.getCause(Cause.UserIdCause)
        if (realUpstreamCause) {
          realUpstreamCause.getUserId()
        }
      }
    }
  }
}

@Lunik
Copy link

Lunik commented Nov 16, 2020

thank's !

@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