从 Jenkins 工作流(管道)插件获取登录到 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 plugin?如果是这样,您应该能够 运行
node {
wrap([$class: 'BuildUser']) {
def user = env.BUILD_USER_ID
}
}
或类似。
无需插件也可以做到这一点(假设 JOB_BASE_NAME
和 BUILD_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,returns用户的全名。
//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
}
使其与 Jenkins 管道一起工作:
然后运行以下内容:
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
块中。
我修改了@shawn derik 的响应以使其在我的管道中工作:
stage("preserve build user") {
wrap([$class: 'BuildUser']) {
GET_BUILD_USER = sh ( script: 'echo "${BUILD_USER}"', returnStdout: true).trim()
}
}
然后我可以稍后通过传递它或在与 ${GET_BUILD_USER} 相同的范围内引用该变量。我安装了引用的相同插件。
def jobUserId, jobUserName
//then somewhere
wrap([$class: 'BuildUser']) {
jobUserId = "${BUILD_USER_ID}"
jobUserName = "${BUILD_USER}"
}
//then
println("Started By: ${jobUserName}")
我们正在使用这个插件:Build User Vars Plugin。更多变量可用。
编辑:我重新阅读了这个问题 - 下面只为您提供 用户 运行 构建(其中技术上通常更有趣),不是在前端触发构建的那个(无论是 REST-API 还是 WebUI)。
如果您启用了 Jenkins 模拟,那么我相信结果应该是相同的,否则这只会让您成为在构建机器上拥有 jenkins 代理的用户。
原回答:
另一种方法是
sh 'export jenkins_user=$(whoami)'
缺点:Linux-依赖,难以在单个构建中跨多个代理移植(但是,每个从站的身份验证上下文可能不同)
优点:无需安装插件(在 shared/large Jenkins 实例上可能很棘手)
没有 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
在代理上执行阶段时,Build User Vars 插件很有用。
另一种方法是使用当前构建子句(请参阅 https://code-maven.com/jenkins-get-current-user),当您的阶段设置为 agent none 时,该子句也适用。 =11=]
以下代码受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'
}
我正在使用 Clouldbees 的 Jenkins 中的 Pipeline 插件(之前的名称是 Workflow 插件),我试图在 Groovy 脚本中获取用户名,但我无法实现它。
stage 'checkout svn'
node('master') {
// Get the user name logged in Jenkins
}
您是否尝试安装 Build User Vars plugin?如果是这样,您应该能够 运行
node {
wrap([$class: 'BuildUser']) {
def user = env.BUILD_USER_ID
}
}
或类似。
无需插件也可以做到这一点(假设 JOB_BASE_NAME
和 BUILD_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,returns用户的全名。
//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
}
使其与 Jenkins 管道一起工作:
然后运行以下内容:
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
块中。
我修改了@shawn derik 的响应以使其在我的管道中工作:
stage("preserve build user") {
wrap([$class: 'BuildUser']) {
GET_BUILD_USER = sh ( script: 'echo "${BUILD_USER}"', returnStdout: true).trim()
}
}
然后我可以稍后通过传递它或在与 ${GET_BUILD_USER} 相同的范围内引用该变量。我安装了引用的相同插件。
def jobUserId, jobUserName
//then somewhere
wrap([$class: 'BuildUser']) {
jobUserId = "${BUILD_USER_ID}"
jobUserName = "${BUILD_USER}"
}
//then
println("Started By: ${jobUserName}")
我们正在使用这个插件:Build User Vars Plugin。更多变量可用。
编辑:我重新阅读了这个问题 - 下面只为您提供 用户 运行 构建(其中技术上通常更有趣),不是在前端触发构建的那个(无论是 REST-API 还是 WebUI)。 如果您启用了 Jenkins 模拟,那么我相信结果应该是相同的,否则这只会让您成为在构建机器上拥有 jenkins 代理的用户。
原回答:
另一种方法是
sh 'export jenkins_user=$(whoami)'
缺点:Linux-依赖,难以在单个构建中跨多个代理移植(但是,每个从站的身份验证上下文可能不同)
优点:无需安装插件(在 shared/large Jenkins 实例上可能很棘手)
没有 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
在代理上执行阶段时,Build User Vars 插件很有用。
另一种方法是使用当前构建子句(请参阅 https://code-maven.com/jenkins-get-current-user),当您的阶段设置为 agent none 时,该子句也适用。 =11=]
以下代码受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'
}