Bogricia
Bogricia

Reputation: 31

Jenkins RoleBasedAuthorizationStrategy add user to Role Groovy Script

I am trying to find a groovy script to add an existing user to a Role using RoleBasedAuthorizationStrategy. Any help would be greatly appreciated.

Upvotes: 3

Views: 5102

Answers (1)

Jeff Painter
Jeff Painter

Reputation: 51

I ran into the same need. After doing some web searching and looking at the plugin's code from GitHub, I found one link that provided some insight: https://issues.jenkins-ci.org/browse/JENKINS-23709. Based on that I hacked together a quick Groovy script that assigns a specific user to a specific role. Been awhile since I've done Groovy, so pardon the dust. Feel free to use this as an example for your own needs.

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!"
}

Upvotes: 5

Related Questions