从Jenkins Workflow(Pipeline)插件获取登录Jenkins的用户名

问题描述 投票:19回答:8

我在Jenkins by Clouldbees中使用了Pipeline插件(之前的名称是Workflow插件),我试图在Groovy脚本中获取用户名但我无法实现它。

stage 'checkout svn'

node('master') {
      // Get the user name logged in Jenkins
}
jenkins groovy jenkins-pipeline cloudbees
8个回答
38
投票

你尝试安装Build User Vars plugin了吗?如果是这样,你应该能够运行

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

或类似的。


11
投票

没有插件就可以做到这一点(假设JOB_BASE_NAMEBUILD_ID在环境中):

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()

还有一个getUserName,它返回用户的全名。


11
投票

使其适用于Jenkins管道:

安装user build vars plugin

然后运行以下命令:

pipeline {
  agent any

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

10
投票

这是一个略短的版本,不需要使用环境变量:

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

rawBuild的使用要求它在@NonCPS块中。


2
投票
//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
}

1
投票
def jobUserId, jobUserName
//then somewhere
wrap([$class: 'BuildUser']) {
    jobUserId = "${BUILD_USER_ID}"
    jobUserName = "${BUILD_USER}"
}
//then
println("Started By: ${jobUserName}")

我们使用的是这个插件:Build User Vars Plugin。有更多变量可供使用。


1
投票

编辑:我重新阅读了这个问题 - 下面只介绍运行构建的用户(技术上通常更有趣),而不是触发前端构建的用户(无论是REST-API还是WebUI)。如果你启用了Jenkins模拟,那么我相信结果应该是等效的,否则这只会让你在构建机器上拥有jenkins代理的用户。

原始答案:

另一种方式是

sh 'export jenkins_user=$(whoami)'

缺点:依赖于Linux,难以在单个构建中跨多个代理端口(但是,每个从属服务器上的auth上下文可能不同)

好处:无需安装插件(在共享/大型Jenkins实例上可能很棘手)


0
投票

我修改了@shawn derik响应以使其在我的管道中工作:

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

然后我可以通过传递它或在与$ {GET_BUILD_USER}相同的范围内引用该变量。我安装了相同的插件引用。

© www.soinside.com 2019 - 2024. All rights reserved.