Jenkins 2 - 如何从Jenkins Workflow获取用户角色(角色策略插件) - 管道插件

时间:2016-09-27 12:56:10

标签: jenkins jenkins-plugins jenkins-pipeline

我想访问在Jenkins 2管道(工作流程)中的角色策略插件中配置的用户角色/角色:

SharedPreferenceManager

1 个答案:

答案 0 :(得分:1)

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()
            }
        }
    }
}