Get username logged in Jenkins from Jenkins Workflow (Pipeline) Plugin

后端 未结 10 621
忘了有多久
忘了有多久 2020-12-25 12:36

I am using the Pipeline plugin in Jenkins by Clouldbees (the name was Workflow plugin before), I am trying to get the user name in the Groovy script but I am not able to ach

相关标签:
10条回答
  • 2020-12-25 12:46

    The Build User Vars Plugin is useful when you are executing the stage on an agent.

    The alternative is to use the current build clause (see https://code-maven.com/jenkins-get-current-user), which also works when your stage is set with agent none.

    0 讨论(0)
  • 2020-12-25 12:48

    It is possible to do this without a plugin (assuming JOB_BASE_NAME and BUILD_ID are in the environment):

    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()
    

    There is also a getUserName, which returns the full name of the user.

    0 讨论(0)
  • 2020-12-25 12:56

    Here's a slightly shorter version that doesn't require the use of environment variables:

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

    The use of rawBuild requires that it be in a @NonCPS block.

    0 讨论(0)
  • 2020-12-25 12:58

    To make it work with Jenkins Pipeline:

    Install user build vars plugin

    Then run the following:

    pipeline {
      agent any
    
      stages {
        stage('build user') {
          steps {
            wrap([$class: 'BuildUser']) {
              sh 'echo "${BUILD_USER}"'
            }
          }
        }
      }
    }
    
    0 讨论(0)
  • 2020-12-25 12:59

    I modified @shawn derik response to get it to work in my pipeline:

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

    Then I can reference that variable later on by passing it or in the same scope as ${GET_BUILD_USER} . I installed the same plugin referenced.

    0 讨论(0)
  • 2020-12-25 13:01

    Did you try installing the Build User Vars plugin? If so, you should be able to run

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

    or similar.

    0 讨论(0)
提交回复
热议问题