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

时间:2016-03-09 21:09:13

标签: jenkins groovy jenkins-pipeline cloudbees

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

stage 'checkout svn'

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

10 个答案:

答案 0 :(得分:37)

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

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

或类似。

答案 1 :(得分: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,它返回用户的全名。

答案 2 :(得分:11)

使其适用于Jenkins Pipeline:

安装user build vars plugin

然后运行以下命令:

pipeline {
  agent any

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

答案 3 :(得分:10)

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

length

使用i1 <- is.na(df1$value) n <- sum(i1) rbind(df1[!i1,], data.frame(value = rep(replace_values, n), result = rep(df1$result[i1], each = length(replace_values)))) # value result #1 3 5 #2 4 3 #3 A 1 #4 B 1 #5 C 1 #6 A 2 #7 B 2 #8 C 2 要求它位于@NonCPS def getBuildUser() { return currentBuild.rawBuild.getCause(Cause.UserIdCause).getUserId() } 块中。

答案 4 :(得分: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
}

答案 5 :(得分: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。有更多可用变量。

答案 6 :(得分:1)

编辑:我重新阅读了问题-以下内容仅使您成为运行该版本的用户(从技术上讲,这通常更有趣),而一个在前端(无论是REST-API还是WebUI)触发构建。 如果您启用了Jenkins模拟功能,那么我相信结果应该是相同的,否则,这只会​​使您拥有在构建计算机上拥有jenkins代理的用户。

原始答案:

另一种方法是

sh 'export jenkins_user=$(whoami)'

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

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

答案 7 :(得分:0)

我修改了@shawn derik响应,让它在我的管道中工作:

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

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

答案 8 :(得分:0)

这对于没有Build User插件的用户来说是有效的:

// 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

答案 9 :(得分:0)

在代理上执行阶段时,Build User Vars插件非常有用。

另一种方法是使用当前的build子句(请参见https://code-maven.com/jenkins-get-current-user),当您的舞台设置为 agent none 时,该子句也可以使用。