Get user name from Jenkins Workflow (Pipeline) Plu

2019-02-03 02:43发布

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
}

7条回答
疯言疯语
2楼-- · 2019-02-03 03:21

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.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-02-03 03:21
//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
}
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-02-03 03:22

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.

查看更多
Emotional °昔
5楼-- · 2019-02-03 03:27

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.

查看更多
Melony?
6楼-- · 2019-02-03 03:36

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}"'
        }
      }
    }
  }
}
查看更多
淡お忘
7楼-- · 2019-02-03 03:39

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.

查看更多
登录 后发表回答