kubectl and seeing (cluster)roles assigned to subjects

4/3/2017

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?

-- Jeroen Jacobs
kubectl
kubernetes

1 Answer

4/3/2017

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
-- Jordan Liggitt
Source: StackOverflow