我在 JOB 下有以下脚本,它在运行时将 userId 添加到从站的标签中。
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 有这个问题吗?我正在使用詹金斯 1.573
相关问题:
更新:
我通过跟踪和错误找到了答案。
User.get(label)
如果默认情况下不存在,则将标签添加为用户。为了防止这种添加,我们必须使用
User.get(label, false)