Jenkins RoleBasedAuthorizationStrategy将用户添加到Role Groovy Script

时间:2016-08-18 17:05:48

标签: jenkins groovy

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

1 个答案:

答案 0 :(得分:4)

我遇到了同样的需要。在进行一些网络搜索并查看来自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!"
}