I have this expression in Jenkins:
println User.current().toString()
In Jenkins script console it returns me the real user value which currently logged in. When I use this function in pipeline script, it returns me the value SYSTEM. any idea why? How I can't I get also here the real user who's logged in?
CodePudding user response:
To answer your last question: 2 simple ways to get a user(name), who's really logged (and also who triggers a build) within the pipeline comes to my mind:
A) Use a plugin - Build user vars (I can recommend it as it is widely used and never failed me):
Here's a code snippet from their official docs. It can be of course used also within declarative pipeline within some stage... This plugins sets several variables that you can use
BUILD_USER
(contains full name),BUILD_USER_ID
(contain user ID) and more (see docs on the plugin page).
node {
wrap([$class: 'BuildUser']) {
def user = env.BUILD_USER_ID
}
}
and/or example of a stage in a declarative pipeline:
stage('User ID') {
steps {
echo "User ID: ${env.BUILD_USER_ID}"
}
}
- B) Use jenkins core methods
def build = currentBuild.rawBuild
def cause = build.getCause(hudson.model.Cause.UserIdCause.class)
def name = cause.getUserName()
echo "User: " name
Note: both approaches (A and B) should work directly within pipelines and within JSL (Jenkins shared library).
To answer also your question from the title: Using your exact method is a problematic and doesn't work for a pipeline script (see old discussions here with more details How to get Jenkins logged user or even official community ticket https://issues.jenkins.io/browse/JENKINS-14605.
Further reading: Following link contains also several tips and approaches how to deal with specific situation of a user name varialbes when the build is triggered by a timer (cron) etc.: How to get the BUILD_USER in Jenkins when job triggered by timer?