Get username logged in Jenkins from Jenkins Workflow (Pipeline) Plugin

Viewed 78734

I am using the Pipeline plugin in Jenkins by Clouldbees (the name was Workflow plugin before), I am trying to get the user name in the Groovy script but I am not able to achieve it.

stage 'checkout svn'

node('master') {
      // Get the user name logged in Jenkins
}
11 Answers

To make it work with Jenkins Pipeline:

Install user build vars plugin

Then run the following:

pipeline {
  agent any

  stages {
    stage('build user') {
      steps {
        wrap([$class: 'BuildUser']) {
          sh 'echo "${BUILD_USER}"'
        }
      }
    }
  }
}

This works for me without the Build User plugin:

// get first entry of JSONArray
def buildCause = currentBuild.getBuildCauses()[0]
def buildPrincipal = [type:"unknown", name:""]

if (buildCause._class ==~ /.+BranchEventCause/) {
  def branchCause = currentBuild.getRawBuild().getCause(jenkins.branch.BranchEventCause)
  buildPrincipal = [type:"branch",name:buildCause.shortDescription]

} else
if (buildCause._class ==~ /.+TimerTriggerCause/) {
  def timerCause = currentBuild.getRawBuild().getCause(hudson.triggers.TimerTrigger.TimerTriggerCause)
  buildPrincipal = [type:"timer", name:"Timer event"]

} else
if (buildCause._class ==~ /.+UserIdCause/) {
  def buildUserCause = currentBuild.getRawBuild().getCause(hudson.model.Cause.UserIdCause)
  buildPrincipal = [type:"user", name:buildCause.userId]

} else
// ... other causes
def jobUserId, jobUserName
//then somewhere
wrap([$class: 'BuildUser']) {
    jobUserId = "${BUILD_USER_ID}"
    jobUserName = "${BUILD_USER}"
}
//then
println("Started By: ${jobUserName}")

We were using this plugin : Build User Vars Plugin. More variables are available.

Edit: I re-read the question - the below only gets you the user running the build (which technically is often more interesting), not the one triggering the build in the frontend (be it REST-API or WebUI). If you have Jenkins impersonation enabled, then I believe the result should be equivalent, otherwise this will only get you the user who owns the jenkins agent on the build machine.

Original answer:

Another way would be to

sh 'export jenkins_user=$(whoami)'

Downside: Linux-dependent, difficult to port across multiple agents in a single build (but then, the auth context may be different on each slave)

Upside: No need to install plugins (which on shared/large Jenkins instances can be tricky)

The Build User Vars Plugin is useful when you are executing the stage on an agent.

The alternative is to use the current build clause (see https://code-maven.com/jenkins-get-current-user), which also works when your stage is set with agent none.

The following code is inspired by Juergen's solution but I added more possible trigger reason and display them in a formatted manner:

String getTriggerReason() {
  def buildCause = currentBuild.getBuildCauses()[0]
  if (buildCause._class ==~ /.+(BranchEventCause|BranchIndexingCause)/) {
    if (env.JOB_BASE_NAME == 'master') {
      return 'Triggered by master commit'
    } else {
      return "Triggered by ${buildCause.shortDescription}"
    }
  }
  if (buildCause._class ==~ /.+TimerTriggerCause/) {
    return 'Triggered by timer'
  }
  if (buildCause._class ==~ /.+BuildUpstreamCause/) {
    return "Triggered by build #${buildCause.upstreamBuild}"
  }
  if (buildCause._class ==~ /.+UserIdCause/) {
    def userName = buildCause.userName.replaceFirst(/\s?\(.*/, '')
    return "Triggered by user ${userName}"
  }
  return 'Unknown trigger'
}
Related