gpt4 book ai didi

Jenkins RoleBasedAuthorizationStrategy 将用户添加到角色 Groovy 脚本

转载 作者:行者123 更新时间:2023-12-01 19:59:01 24 4
gpt4 key购买 nike

我正在尝试找到一个常规脚本来使用 RoleBasedAuthorizationStrategy 将现有用户添加到角色。任何帮助将不胜感激。

最佳答案

我也遇到了同样的需求。在进行了一些网络搜索并查看了 GitHub 上的插件代码后,我发现了一个提供了一些见解的链接:https://issues.jenkins-ci.org/browse/JENKINS-23709 。基于此,我编写了一个快速的 Groovy 脚本,将特定用户分配给特定角色。我已经有一段时间没有使用 Groovy 了,所以请原谅我的灰尘。请随意使用此示例来满足您自己的需求。

import jenkins.model.*
import hudson.security.*
import java.util.*
import com.michelin.cio.hudson.plugins.rolestrategy.*
import java.lang.reflect.*

def roleName = "guest"
def userName = "bot-release"

def findGuestRoleEntry(grantedRoles, roleName)
{
for (def entry : grantedRoles)
{
Role role = entry.getKey()

if (role.getName().equals(roleName))
{
return entry
}
}

return null
}

def authStrategy = Jenkins.instance.getAuthorizationStrategy()

if(authStrategy instanceof RoleBasedAuthorizationStrategy){
RoleBasedAuthorizationStrategy roleAuthStrategy = (RoleBasedAuthorizationStrategy) authStrategy

// Make constructors available
Constructor[] constrs = Role.class.getConstructors();
for (Constructor<?> c : constrs) {
c.setAccessible(true);
}
// Make the method assignRole accessible
Method assignRoleMethod = RoleBasedAuthorizationStrategy.class.getDeclaredMethod("assignRole", String.class, Role.class, String.class);
assignRoleMethod.setAccessible(true);

def grantedRoles = authStrategy.getGrantedRoles(RoleBasedAuthorizationStrategy.GLOBAL);
if (grantedRoles != null)
{
// println "Got grantedRoles for " + RoleBasedAuthorizationStrategy.GLOBAL

def roleEntry = findGuestRoleEntry(grantedRoles, roleName);
if (roleEntry != null)
{
// println "Found role " + roleName

def sidList = roleEntry.getValue()
if (sidList.contains(userName))
{
println "User " + userName + " already assigned to role " + roleName
} else {
println "Adding user " + userName + " to role " + roleName
roleAuthStrategy.assignRole(RoleBasedAuthorizationStrategy.GLOBAL, roleEntry.getKey(), userName);
println "OK"
}

Jenkins.instance.save()
} else {
println "Unable to find role " + roleName
}
} else {
println "Unable to find grantedRoles for " + RoleBasedAuthorizationStrategy.GLOBAL
}
} else {
println "Role Strategy Plugin not found!"
}

关于Jenkins RoleBasedAuthorizationStrategy 将用户添加到角色 Groovy 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39023844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com