3

I have Jenkins job with active choice parameter with the name Computer. Which groovy script I should write to bring me all the Nodes names, and present only the one for the current logged in user? All nodes are with the label Desktop. I tried the below but it doesn't work:

import hudson.slaves.DumbSlave def users = [] for (DumbSlave it : Hudson.instance.getSlaves()) { if(it.getLabelString().contains("Desktop")) { def currAgent = it?.computer?.name if(currAgent != null) { users.add(currAgent) } } } return users 

Update (full answer with logged-on user, based on the below answer):

import jenkins.model.* import hudson.model.User def users = [] Jenkins.instance.nodes.each { node -> if(node.labelString.contains("Desktop")) { def currAgent = node?.computer def currAgentName = node?.computer?.name if(currAgentName != null) { def user = currAgent.systemProperties['user.name']?.toLowerCase() if (!users.contains(user) && user==User.current().toString()){ users.add(currAgentName) } } } } return users 
4
  • what do you mean by logged in user? logged in to Jenkins? the user who triggers the build? note that you defined a List def users = [] but used it as Map users.containsKey.. and IMO you should return a List at the end. Commented Nov 7, 2021 at 13:36
  • logged in to Jenkins. I agree I should return a list for active choice instead of map... Commented Nov 7, 2021 at 13:41
  • then I think that you are interested in stackoverflow.com/a/24167308/947784 and not in computer.systemProperties['user.name'] Commented Nov 7, 2021 at 13:44
  • Tnx! I added full answer in my question Commented Nov 8, 2021 at 17:56

1 Answer 1

5

Try this:

import jenkins.model.* def users = [] Jenkins.instance.nodes.each { node -> if(node.labelString.contains("Desktop")) { def currAgent = node?.computer?.name if(currAgent != null) { users.add(currAgent) } } } return users 

Or make it Groovyer:

import jenkins.model.* return Jenkins.instance.nodes.findAll { node -> node.labelString.contains("Desktop") && node.computer.systemProperties["user.name"] == User.current().toString() }.collect { node -> node?.computer?.name } 
Sign up to request clarification or add additional context in comments.

1 Comment

Tnx! I added full answer in my question

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.