0

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?

1 Answer 1

1

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?

Sign up to request clarification or add additional context in comments.

2 Comments

Tnx for the info. So to summarize my case, there is no way to get current logged on user in pipeline script?
Maybe let's clarify what exactly do you mean and understand under a "logged user"? If a user X logs in and triggers a build, then both A) and B) approaches that I shown would display the ID of user X (or name, or first name etc) of the logged user who triggered it in a log.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.