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

倖福魔咒の 提交于 2019-11-30 11:55:49

问题


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
}

回答1:


Did you try installing the Build User Vars plugin? If so, you should be able to run

node {
  wrap([$class: 'BuildUser']) {
    def user = env.BUILD_USER_ID
  }
}

or similar.




回答2:


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}"'
        }
      }
    }
  }
}



回答3:


It is possible to do this without a plugin (assuming JOB_BASE_NAME and BUILD_ID are in the environment):

def job = Jenkins.getInstance().getItemByFullName(env.JOB_BASE_NAME, Job.class)
def build = job.getBuildByNumber(env.BUILD_ID as int)
def userId = build.getCause(Cause.UserIdCause).getUserId()

There is also a getUserName, which returns the full name of the user.




回答4:


Here's a slightly shorter version that doesn't require the use of environment variables:

@NonCPS
def getBuildUser() {
    return currentBuild.rawBuild.getCause(Cause.UserIdCause).getUserId()
}

The use of rawBuild requires that it be in a @NonCPS block.




回答5:


//Below is a generic groovy function to get the XML metadata for a Jenkins build.
//curl the env.BUILD_URL/api/xml parse it with grep and return the string
//I did an or true on curl, but possibly there is a better way
//echo -e "some_string \c" will always return some_string without \n char     
//use the readFile() and return the string
def GetUserId(){
 sh """
 /usr/bin/curl -k -s -u \
 \$USERNAME:\$PASSWORD -o \
 /tmp/api.xml \
 \$BUILD_URL/api/xml || true 

 THE_USERID=`cat /tmp/api.xml | grep -oP '(?<=<userId>).*?(?=</userId>)'`
 echo -e "\$THE_USERID \\c" > /tmp/user_id.txt                               
 """
def some_userid = readFile("/tmp/user_id.txt")
some_userid
}



回答6:


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.




回答7:


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)




回答8:


I modified @shawn derik response to get it to work in my pipeline:

    stage("preserve build user") {
            wrap([$class: 'BuildUser']) {
                GET_BUILD_USER = sh ( script: 'echo "${BUILD_USER}"', returnStdout: true).trim()
            }
        }

Then I can reference that variable later on by passing it or in the same scope as ${GET_BUILD_USER} . I installed the same plugin referenced.



来源:https://stackoverflow.com/questions/35902664/get-username-logged-in-jenkins-from-jenkins-workflow-pipeline-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!