Kubernetes ServiceAccount cannot list nodes

5/1/2020

I'm trying to give my service account foo permissions to get a list of the nodes on the cluster (via kubectl get nodes). I created a clusterrole and a role binding with these permissions:

apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRole
metadata:
 name: foo-cluster-role
rules:
  - apiGroups: [""]
    resources: ["nodes"]
    verbs: ["get", "list", "watch"]

When I run a pod with that service account I'm unable to run kubectl get nodes:

root@debugger:/# kubectl get nodes
Error from server (Forbidden): nodes is forbidden: User "system:serviceaccount:default:foo" cannot list resource "nodes" in API group "" at the cluster scope

Weirdly, when I ask via kubectl auth can-i, it tells me I should have access:

root@debugger:/# kubectl auth can-i get nodes
Warning: resource 'nodes' is not namespace scoped
yes

How do I set up my serviceaccount so I have access to list the nodes on the cluster?

edit clusterrolebinding looks like this:

kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: foo-binding
subjects:
- kind: ServiceAccount
  name: foo
roleRef:
  kind: ClusterRole
  name: foo-cluster-role
  apiGroup: ""
-- spike
kubernetes

1 Answer

5/2/2020

You have to create ClusterRoleBinding. Please check with following.

    apiVersion: rbac.authorization.k8s.io/v1beta1
    kind: ClusterRole
    metadata:
      name: foo-cluster-role
    rules:
    - apiGroups: [""]
      resources: ["nodes"]
      verbs: ["get", "watch", "list"]

    ---
    apiVersion: rbac.authorization.k8s.io/v1beta1
    kind: ClusterRoleBinding
    metadata:
      name: foo-binding
    subjects:
    - kind: ServiceAccount
      name: foo
    roleRef:
      kind: ClusterRole
      name: foo-cluster-role
      apiGroup: rbac.authorization.k8s.io
-- hoque
Source: StackOverflow