RBAC and service accounts

Kubernetes · Advanced · 12 min

A cluster without tight RBAC lets any compromised pod or laptop do anything.

Every API request is made by a subject: a user (from your identity provider or certificates), a group, or a ServiceAccount (an identity for pods). RBAC decides what it may do. Permissions are additive; there are no deny rules.

  • A Role lists rules in one namespace: apiGroups, resources, verbs (get, list, watch, create, update, patch, delete), optionally specific resourceNames.
  • A ClusterRole is the same but not namespaced: for cluster-scoped resources, or as a reusable rule set.
  • A RoleBinding grants a Role or ClusterRole to subjects within one namespace.
  • A ClusterRoleBinding grants a ClusterRole across the whole cluster.

Built-in ClusterRoles view, edit and admin cover common needs; bind them per namespace with a RoleBinding.

Pods run as the namespace's default ServiceAccount unless you set serviceAccountName. Their token is mounted as a short-lived, auto-rotated projected token; set automountServiceAccountToken: false when a pod never calls the API.

Check permissions with kubectl auth can-i list secrets -n shop --as=system:serviceaccount:shop:web.

Dangerous grants: list or get on secrets, create on pods (can mount any secret or run privileged), escalate/bind, impersonate, and wildcards.

Example

apiVersion: v1
kind: ServiceAccount
metadata: {name: deployer, namespace: shop}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata: {name: deploy-updater, namespace: shop}
rules:
  - apiGroups: ["apps"]
    resources: ["deployments"]
    verbs: ["get", "list", "patch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata: {name: deployer-can-update, namespace: shop}
subjects:
  - {kind: ServiceAccount, name: deployer, namespace: shop}
roleRef: {kind: Role, name: deploy-updater, apiGroup: rbac.authorization.k8s.io}
# kubectl auth can-i patch deploy -n shop --as=system:serviceaccount:shop:deployer  # yes
# kubectl auth can-i delete deploy -n shop --as=system:serviceaccount:shop:deployer # no

Remember

  • Role/ClusterRole say what; bindings say who and where
  • RBAC is additive: no deny rules
  • kubectl auth can-i --as tests any subject

Watch out for

  • Granting cluster-admin to a CI service account because a narrower Role took effort.

Check yourself

  1. You want a ClusterRole's rules to apply in only one namespace. What do you create?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: kubernetes.io/docs/reference/access-authn-authz/rbac/