jenkins Slave API setLabelString添加到用户列表

时间:2015-03-10 19:25:21

标签: groovy jenkins automation jenkins-scriptler

我在JOB下有以下脚本,运行时会将userId添加到slave的标签中。

import jenkins.model.Jenkins
import hudson.model.User
import hudson.security.Permission
import hudson.EnvVars

EnvVars envVars = build.getEnvironment(listener);

def userId= envVars .get('BUILD_USER_ID')
def nodeName= envVars .get('NODE_NAME')
def nodeOffpool= envVars .get('NODE_GOING_OFFPOOL')

allUsers = User.getAll()
println allUsers
println ""

// add userid as a label if doesnot exist
for (slave in hudson.model.Hudson.instance.slaves) {
  if( slave.nodeName.equals(nodeOffpool)) {

  def labelList = (slave.getLabelString()).split()
  println labelList
  // check for user access to machine
  for(label in labelList) {
       println (User.get(label))
       println (User.get(label) in allUsers)
       if (User.get(label) in allUsers) {
            if (label == userId) {
                 println ("This Node has already been assigned to you ($userId)")
            } else {
                 println ("This Node($nodeOffpool) has already been assigned to someone($label) else, you cannot use it now")
                 println ("Please ask the user $label  to release the Node($nodeOffpool)  for you($label) to run")
            }
            return
       }
  };
  println ("before: " + slave.getLabelString())
  // setting the slave with new label
  String newLabel = slave.getLabelString() + " " + userId 
  slave.setLabelString(newLabel)
  println ("after: " + slave.getLabelString())
  }
}

当我第一次跑步时输出看起来很好

[user1, user2, SYSTEM, unknown]
[TESTLAB3, TESTLAB4]
TESTLAB3
false
TESTLAB4
false
before: TESTLAB3 TESTLAB4
after: TESTLAB3 TESTLAB4 user1

当我第二次跑步时

[user1, user2, SYSTEM, unknown, TESTLAB3, TESTLAB4]
[TESTLAB3, TESTLAB4, user1]
TESTLAB3
true
This Node(node1) has already been assigned to someone(TESTLAB3) else, you cannot use it now
Please ask the user TESTLAB3  to release the Node(node1)  for you(TESTLAB3) to run
Finished: SUCCESS

这是Jenkins API的问题吗?我正在使用Jenkins 1.573

相关问题:

  1. How to identify admins on Jenkins using groovy scripts
  2. jenkins change label as requested
  3. 更新:

    我通过追踪和错误找到答案。

    User.get(label)
    
    如果标签默认不存在,则

    将标签添加为用户。为了防止这种添加,我们必须使用

    User.get(label, false)
    

1 个答案:

答案 0 :(得分:1)

您正在将用户名添加到奴隶的标签中。打印User.getAll()只打印Jenkins的用户列表,而不是用用户名修改的slave标签。

这是一个脚本,您可以使用它来测试您的从属计算机是否添加了新标签:

for (slave in jenkins.model.Jenkins.instance.slaves) {
  print "Slave: " + slave.getNodeName() + "\n";  
  print "Label: " + slave.getLabelString() + "\n\n";
}

此外,您可能希望更改脚本,以便它只为Slave设置新标签(如果它还没有包含用户),因为每次运行脚本时您都会多次添加它它现在写的方式。