🎓 A1Learner
🔍
0 of 51 lessons completed

Kubernetes: Service Accounts and RBAC

A ServiceAccount is an identity for a pod or a job. RBAC is the rule book that says which identities may do what. A RoleBinding hands out those rules in one namespace.

A ServiceAccount

A ServiceAccount is an identity, like a badge. A pod that runs with it speaks to the cluster as that identity. Without one, a pod uses the default account.

apiVersion: v1
kind: ServiceAccount
metadata:
  name: reader
  namespace: default

A Role that only reads pods

A Role names what an identity may do. This one allows get and list on pods only. It allows nothing else, and it works only in its own namespace.

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: pod-reader
  namespace: default
rules:
  - apiGroups: [""]
    resources: ["pods"]
    verbs: ["get", "list"]

A RoleBinding that links the two

A RoleBinding links the Role to the ServiceAccount. The reader account may now list pods in this namespace. The same Role in another namespace would need its own binding.

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: read-pods
  namespace: default
subjects:
  - kind: ServiceAccount
    name: reader
roleRef:
  kind: Role
  name: pod-reader
  apiGroup: rbac.authorization.k8s.io

Example

kubectl apply -f reader-rbac.yaml
kubectl auth can-i get pods --as=system:serviceaccount:default:reader

Key points

  • ServiceAccount: an identity that a pod uses to talk to the cluster
  • Role: a list of allowed actions inside one namespace
  • ClusterRole: a list of allowed actions across the whole cluster
  • RoleBinding: the link that gives a Role to an identity in one namespace
  • ClusterRoleBinding: the link that gives a ClusterRole to an identity across the cluster
  • Use the smallest Role that does the job, and never hand out more access than needed

In this example, the first command creates a ServiceAccount, a Role and a RoleBinding from the file. The second command asks whether that account may list pods. The answer is yes, which proves the RoleBinding gave the account exactly that permission.

Note

RBAC checks the identity, not the person, so a pod needs its own ServiceAccount

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

What is the difference between a RoleBinding and a ClusterRoleBinding?