Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kubectl and seeing (cluster)roles assigned to subjects

I can use kubectl to see to which subjects a cluster role is applied, eg:

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"
        }
    ]
}

I would like to get this info the other way around, eg: I want to list all policies applied to the "system:nodes" subject.

How can I do that?

like image 724
Jeroen Jacobs Avatar asked Apr 03 '17 13:04

Jeroen Jacobs


1 Answers

There is no API for the reverse index. You can look up bindings and filter on ones containing the expected subject. For example, using bash, jq, and kubectl:

# $1 is kind (User, Group, ServiceAccount)
# $2 is name ("system:nodes", etc)
# $3 is namespace (optional, only applies to kind=ServiceAccount)
function getRoles() {
    local kind="${1}"
    local name="${2}"
    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
like image 58
Jordan Liggitt Avatar answered Sep 23 '22 03:09

Jordan Liggitt