[3] Jenkins 系列:如何获取出发Jenkins Job的用户信息?_jenkins 获取用户名

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

Jenkins提供两种方式的Script一种是基于声明式的一种是基于脚本式的。

  • Jenkins申明式的格式
    在这里插入图片描述
  • Jenkins脚本式的格式
    在这里插入图片描述
    Jenkins 官方推荐使用申明式的方式定义Jenkins的Pipeline。

有的时候我们需要在Pipeline给开发团队发消息或者邮件告知当前Pipeline是谁触发的这个时候在脚本里面应该如何获取当前触发人的信息呢Jenkins提供了很多种方式下面笔者简单罗列一下

1.通过Buid User Var

此为Build user var 的官方地址 https://plugins.jenkins.io/build-user-vars-plugin/ 在Jenkins安装此插件但是不需要重启Jenkins, 其可以获取下面的有关用户的信息

在这里插入图片描述
脚本使用方式

node {
  def user=""
  def userEmail=""
  wrap([$class: 'BuildUser']) {
    user = env.BUILD_USER_ID
    userEmail = env.BUILD_USER_EMAIL
  }
  echo "The user name ${user }"
  echo "The user email ${userEmail }"
}

2.通过Groovy 脚本

如果不想安装插件也可以直接通过Groovy的脚本获取。

方法1

node('master') {
BUILD_TRIGGER_BY = sh ( script: "BUILD_BY=\$(curl -k --silent ${BUILD_URL}/api/xml | tr '<' '\n' | egrep '^userId>|^userName>' | sed 's/.*>//g' | sed -e '1s/\$/ \\/ /g'); if [[ -z \${BUILD_BY} ]]; then BUILD_BY=\$(curl -k --silent ${BUILD_URL}/api/xml | tr '<' '\n' | grep '^shortDescription>' | sed 's/.*user //g;s/.*by //g'); fi; echo \${BUILD_BY}", returnStdout: true ).trim()
echo "BUILD_TRIGGER_BY: ${BUILD_TRIGGER_BY}"
}

方法2

BUILD_TRIGGER_BY = "${currentBuild.getBuildCauses()[0].shortDescription} / ${currentBuild.getBuildCauses()[0].userId}"
echo "BUILD_TRIGGER_BY: ${BUILD_TRIGGER_BY}"

3.通过Shell脚本

此外也可以通过shell的curl命令调用Jenkins Rest的API获取用户信息。

BUILD_TRIGGER_BY=$(curl -k --silent ${BUILD_URL}/api/xml | tr '<' '\n' | egrep '^userId>|^userName>' | sed 's/.*>//g' | sed -e '1s/$/ \//g' | tr '\n' ' ')
echo "BUILD_TRIGGER_BY: ${BUILD_TRIGGER_BY}"

4.总结

道路千万条笔者最喜欢的还是第一种方式通过插件的方式。

参考文献

https://plugins.jenkins.io/build-user-vars-plugin/
https://stackoverflow.com/questions/36194316/how-to-get-the-build-user-in-jenkins-when-job-triggered-by-timer
https://www.jenkins.io/doc/book/pipeline/
https://www.jenkins.io/doc/book/pipeline/syntax/

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6