codependent
codependent

Reputation: 24452

Jenkins 2 - How to get user role (Role Strategy Plugin) from Jenkins Workflow - Pipeline Plugin

I would like to access the user role/roles, configured in Role Strategy Plugin in a Jenkins 2 pipeline (workflow):

node {
      // Get the user Role
}

Upvotes: 5

Views: 2869

Answers (1)

Laino Santos
Laino Santos

Reputation: 86

import jenkins.model.Jenkins
import com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy
import com.michelin.cio.hudson.plugins.rolestrategy.Role

node {
    stage('Get Role') {
        def user  = Jenkins.getInstance().getUser(
            Jenkins.getInstance().getItemByFullName(env.JOB_BASE_NAME, Job.class).getBuildByNumber(env.BUILD_ID as int).getCause(Cause.UserIdCause).getUserId()
        )
        def authorization = Jenkins.getInstance().getAuthorizationStrategy()
        //RoleBasedAuthorizationStrategy.{GLOBAL, PROJECT, SLAVE, MACRO_ROLE, MACRO_USER}
        def grantedRoles = authorization.getGrantedRoles(RoleBasedAuthorizationStrategy.GLOBAL)

        for (Role grantedRole : grantedRoles.entrySet()) {
            if (grantedRole.getValue().contains(user.getId())) {
                echo grantedRole.getKey().getName()
            }
        }
    }
}

Upvotes: 4

Related Questions