Jenkins在管道中获得当前用户

44u64gxh  于 2023-03-07  发布在  Jenkins
关注(0)|答案(3)|浏览(358)

我在Jenkins pipeline中有一个要求,在成功构建后,我需要用户输入来继续或中止。开发人员只打算部署到开发环境中,运营人员可以在QA和生产上进行部署。
我的问题是,如果我以开发人员身份登录Jenkins,并在构建后执行QA或生产的构建和部署,那么它应该显示一条消息,即未授权在QA或生产上进行部署。开发团队将通知运营团队在管道中进行进一步部署。运营人员将使用他们的凭据登录,当他们触发部署到QA或生产的过程或中止时,它应该发生。

我的问题是如何获取Jenkins的当前登录用户,以便验证用户并继续部署。

stage('confirmDeploy'){
  inputMessage("${TARGET_PLATFORM}")
  echo "Deploying release on ${TARGET_PLATFORM} environment"
} 
def inputMessage(String inputEnvName) {
  timeout(time: 1, unit: 'HOURS') {
    input message: "Are you sure to promote this build to ${inputEnvName} env ?", ok: 'deploy'
    wrap([$class: 'BuildUser']) {
      sh 'echo "${BUILD_USER}"'
      if (( "${inputEnvName}" == "qa" && "${BUILD_USER}" == "ops")||( "${inputEnvName}" == "prod" && "${BUILD_USER}" == "ops")){
       input message: "Are you sure to promote this build to ${inputEnvName} env ?", ok: 'deploy'}
      else if (( "${inputEnvName}" == "dev" && "${BUILD_USER}" =="devuser")){
        input message: "Are you sure to promote this build to ${inputEnvName} env ?", ok: 'deploy'}
      else { 
        echo 'Further code will not be executed'echo "Not authorized to carry deployment to the respective environment", ok: 'deploy' 
      }
    }
  }
}
w51jfk4q

w51jfk4q1#

您需要以下代码:

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

注意:这是假设您已安装https://wiki.jenkins-ci.org/display/JENKINS/Build+User+Vars+Plugin

cxfofazt

cxfofazt2#

您可以使用shell来运行用户id命令,并在Jenkins变量中运行相同的命令。

environment {
         SH_BUILD_USER_ID = sh (
            script: 'id -u',
            returnStdout: true
         ).trim()
         }

其中,“id -u”是用于获取用户ID的Linux命令。您可以使用任何命令获取其数据并在Jenkins管道中使用

8iwquhpp

8iwquhpp3#

尝试以下方法(3种不同的可能方法):

currentBuild.rawBuild.getCause(Cause.UserIdCause).getUserId()

currentBuild
  .getBuildCauses('hudson.model.Cause$UserIdCause')[0]
  ?.userId ?: 'default'

def causes = currentBuild.rawBuild.getCauses()
// loop over each `cause`
  if (cause.class.name == 'hudson.model.Cause$UserIdCause') {
    // use properties of `cause` object.
  }

虽然我还没有确认,但似乎可以从cause对象获得userIduserNameuserId似乎是一些安装的电子邮件地址,尽管可以配置为其他值。

相关问题