繁体   English   中英

从 Jenkins Workflow (Pipeline) Plugin 获取登录用户名 Jenkins

[英]Get username logged in Jenkins from Jenkins Workflow (Pipeline) Plugin

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

stage 'checkout svn'

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

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

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

或类似。

要使其与 Jenkins Pipeline 一起使用:

安装用户构建变量插件

然后运行以下命令:

pipeline {
  agent any

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

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

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

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

可以在没有插件的情况下执行此操作(假设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,它返回用户的全名。

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

我们正在使用这个插件: 构建用户变量插件 更多的变量可用。

在没有 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
//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
}

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

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

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

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

原答案:

另一种方法是

sh 'export jenkins_user=$(whoami)'

缺点:依赖于 Linux,难以在单个构建中跨多个代理移植(但是,每个从属上的身份验证上下文可能不同)

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

当您在代理上执行阶段时,构建用户变量插件非常有用。

另一种方法是使用 current build 子句(请参阅https://code-maven.com/jenkins-get-current-user ),当您的 stage 设置为agent none时,它也适用。

以下代码的灵感来自 Juergen 的解决方案,但我添加了更多可能的触发原因并以格式化的方式显示它们:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM