Skip to main content

How to set up RBAC in Kubernetes with Roles and ServiceAccounts

RBAC grants least-privilege access through Roles and RoleBindings, with workloads authenticating as ServiceAccounts. Define narrow rules, bind them, and verify with kubectl auth can-i.

Difficulty
Intermediate
Duration
40 minutes
Steps
6

RBAC in Kubernetes

Role-based access control (RBAC) decides who can do what in the cluster. Roles define permissions; RoleBindings grant a Role to subjects such as users, groups, or ServiceAccounts. Workloads authenticate as ServiceAccounts, so RBAC governs both humans and pods. The goal is least privilege.

Prerequisites

  • Cluster admin access to create RBAC objects.
  • kubectl configured against the cluster.

Steps

1. Understand RBAC objects

A Role is namespaced; a ClusterRole is cluster-wide. A RoleBinding grants within a namespace; a ClusterRoleBinding grants cluster-wide. Permissions are rules over apiGroups, resources, and verbs.

2. Create a namespaced Role

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

3. Create a ServiceAccount

kubectl create serviceaccount app-sa -n team-a

Pods that should read pods will run as this account.

4. Bind the role

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

5. Use the ServiceAccount in a pod

Set serviceAccountName: app-sa in the pod spec. The pod receives a token mounted automatically and acts with exactly those permissions.

6. Verify with can-i

kubectl auth can-i list pods \
  --as=system:serviceaccount:team-a:app-sa -n team-a

The command returns yes or no for the given action.

Verification

Use kubectl auth can-i to confirm the ServiceAccount can list pods but cannot, for example, delete deployments. Deploy a pod with the account and confirm a permission-denied error if it tries an unauthorized action.

Next Steps

Disable automatic token mounting where pods do not call the API, prefer narrow Roles over broad ClusterRoles, and audit bindings regularly. Combine RBAC with namespaces, network policies, and pod security standards for defense in depth.

Prerequisites

  • Cluster admin access
  • kubectl configured

Steps

  • 1
    Understand RBAC objects
  • 2
    Create a namespaced Role
  • 3
    Create a ServiceAccount
  • 4
    Bind the role
  • 5
    Use the ServiceAccount in a pod
  • 6
    Verify with can-i

Category

Security