Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins: How to get a users LDAP groups in groovy-script

i have setup a parametrized job for self-service deployments in Jenkins. Users can select a version of the application and the environment to deploy to. The available environments displayed to the user is currently just a static list of strings (choice parameter).

Now i want to restrict deployments to some environments based on the LDAP-groups of the current user.

The user-page in jenkins displays something like:

Jenkins Benutzer Id: maku

Groups:

adm_proj_a
nexus_admin
ROLE_ADM_PROJ_XY
ROLE_BH_KK

How do i get these groups within a groovy-script?

I tried to use dynamic choice parameter (scriptler) and get the LDAP-groups using a groovy-script but did not find my way through the Jenkins-API.

Any hints welcome

like image 526
Markus Künstler Avatar asked Jun 18 '14 07:06

Markus Künstler


2 Answers

User.getAuthorities() requires the caller to have the ADMINISTER permission. (http://javadoc.jenkins-ci.org/hudson/model/User.html#getAuthorities())

An alternative is to query the SecurityRealm directly.

import hudson.model.*
import jenkins.model.*

def userid = User.current().id
def auths = Jenkins.instance.securityRealm.loadUserByUsername(userid)
            .authorities.collect{a -> a.authority}
if("adm_proj_a" in auths){
...
like image 98
Lionel Orellana Avatar answered Nov 09 '22 11:11

Lionel Orellana


I found a solution. Just in case anybody is interested:

Within scriptler i created a script groovy-script similar to this:

import hudson.model.*

def allowed_environments = ["dev","test","test-integration"]  

if ("adm_proj_a" in User.current().getAuthorities() ) 
{
   allowed_environments.add("production")
}

 return allowed_environments

This script is used by dynamic choice parameter (scriptler) within my Jenkins-Job.

Now only users within the group adm_proj_a can see production as a choice.

like image 23
Markus Künstler Avatar answered Nov 09 '22 11:11

Markus Künstler