Jenkins Pipeline 中安全获取用户角色的正确实践

在 jenkins pipeline 中直接访问 role-based strategy 插件的授权策略会触发 `notserializableexception`,因 `rolebasedauthorizationstrategy` 对象不可序列化;解决方案是将权限检查逻辑封装为外部可序列化函数,并避免在 `script` 块中直接引用非序列化 jenkins 内部对象。

Jenkins Pipeline 使用 Groovy 编写,其执行引擎要求所有在 script 块中定义并跨阶段/步骤持久化的对象必须实现 java.io.Serializable。而 com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy(即 RoleBasedAuthorizationStrategy)及其关联的 roleMaps、grantedRoles 等内部结构均未实现序列化接口。因此,当您在 script 块内直接调用 Jenkins.instance.getAuthorizationStrategy() 并尝试遍历其状态时,Pipeline 会在序列化检查阶段失败,抛出:

Caused: java.io.NotSerializableException: com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy

✅ 正确做法:将敏感 Jenkins 实例操作移至 pipeline 顶层的 def 函数中(即“全局函数”),该函数

在 Pipeline 编译期解析、运行于 master 节点且不参与分布式序列化流程;而 script 块内仅调用其返回值(如 List 角色名列表),确保数据轻量、可序列化。

以下是推荐的完整实现方式:

pipeline {
    agent any
    environment {
        TIMEOUT = '30'
        RUNNER_USER = 'admin'
    }
    stages {
        stage('Check Admin Permission & Prompt') {
            steps {
                script {
                    def userRoles = getRoles(env.RUNNER_USER)
                    if (userRoles.contains('admin')) {
                        timeout(time: Integer.parseInt(env.TIMEOUT), unit: 'SECONDS') {
                            input(
                                message: "Do you want to overwrite the lock?",
                                ok: "Yes"
                            )
                        }
                    } else {
                        echo "Warning: User '${env.RUNNER_USER}' is not in 'admin' role. Skipping confirmation."
                    }
                    echo "Job finished successfully."
                }
            }
        }
    }
}

// ✅ 定义为 pipeline 顶层函数(非 script 块内),可安全访问 Jenkins 实例
def getRoles(String username) {
    // 注意:此函数在 master 上执行,无需序列化返回值以外的对象
    def authStrategy = Jenkins.instance.getAuthorizationStrategy()

    // 防御性检查:确保使用的是 RoleBasedAuthorizationStrategy
    if (!(authStrategy instanceof com.michelin.cio.hudson.plugins.rolestrategy.RoleBasedAuthorizationStrategy)) {
        error "Expected RoleBasedAuthorizationStrategy, but got ${authStrategy.class.name}"
    }

    // 构建 {Role -> List} 映射:roleMaps 是 Map>>
    // 我们关注的是 Global/Project RoleMap 中的 grantedRoles(类型为 Map>)
    def allGrants = [:]
    authStrategy.roleMaps.values().each { roleMap ->
        roleMap.grantedRoles.each { role, users ->
            allGrants[role] = allGrants.getOrDefault(role, []) + users.toList()
        }
    }

    // 反向查找:哪些 Role 包含当前用户
    def rolesForUser = allGrants.findAll { _, users -> users.contains(username) }
        .keySet()
        .collect { it.name } // 提取 Role 名称(String)

    return rolesForUser
}

? 关键注意事项:

  • ⚠️ 不要在 script 块中直接调用 Jenkins.instance 或持有其子对象(如 authStrategy, roleMaps)——它们不可序列化;
  • ✅ 将 Jenkins API 调用严格限制在顶层 def 函数中,仅返回简单类型(String, List, Boolean);
  • ? getRoles() 函数需运行在 Jenkins Master 节点(默认满足),确保有权限读取全局授权策略;
  • ? 建议添加类型校验(如 instanceof)和空值防护,提升健壮性;
  • ? 若使用 Jenkins 2.387+ 与 Role Strategy Plugin 3.5+,注意 grantedRoles 的实际结构可能因作用域(Global/Project)略有差异,上述示例已兼容主流版本。

通过该模式,您既能安全获取用户所拥有的角色(如 admin),又能完全规避 NotSerializableException,保障 Pipeline 稳定执行。