kubectl 并查看分配给主题的(集群)角色

kubectl and seeing (cluster)roles assigned to subjects

我可以使用 kubectl 查看集群角色应用于哪些主题,例如:

kubectl get clusterrolebindings system:node --all-namespaces -o json                                                                                                                                                                    
{
    "apiVersion": "rbac.authorization.k8s.io/v1beta1",
    "kind": "ClusterRoleBinding",
     ....
     ....
    "subjects": [
        {
            "apiGroup": "rbac.authorization.k8s.io",
            "kind": "Group",
            "name": "system:nodes"
        }
    ]
}

我想以相反的方式获取此信息,例如:我想列出应用于 "system:nodes" 主题的所有政策。

我该怎么做?

反向索引没有API。您可以查找绑定并过滤包含预期主题的绑定。例如,使用 bash、jq 和 kubectl:

#  is kind (User, Group, ServiceAccount)
#  is name ("system:nodes", etc)
#  is namespace (optional, only applies to kind=ServiceAccount)
function getRoles() {
    local kind=""
    local name=""
    local namespace="${3:-}"

    kubectl get clusterrolebinding -o json | jq -r "
      .items[]
      | 
      select(
        .subjects[]?
        | 
        select(
            .kind == \"${kind}\" 
            and
            .name == \"${name}\"
            and
            (if .namespace then .namespace else \"\" end) == \"${namespace}\"
        )
      )
      |
      (.roleRef.kind + \"/\" + .roleRef.name)
    "
}

$ getRoles Group system:authenticated
ClusterRole/system:basic-user
ClusterRole/system:discovery

$ getRoles ServiceAccount attachdetach-controller kube-system
ClusterRole/system:controller:attachdetach-controller