What is RBAC in Kubernetes?

RBAC stands for Role Based Access Control. It allows us to define user privilege in the Kubernetes cluster that will restrict users from doing the unwanted operation. We describe access rights such as who is allowed to create, update, and delete resources.

Why do we need it?

  • To make the cluster more secure.
  • To scale our cluster to various development teams and avoid conflict between them.

Objects

In RBAC API there are main 4 types of objects –

  • Role – It’s used for namespace object constraints.
  • RoleBinding – Mapping the Role to the user.
  • ClusterRole – It’s used for the cluster-wide resource constraints.
  • CLusterRoleBinding – It’s used for mapping the ClusterRole to the user.

Example

Now we are going to create the objects mentioned above and see how these all work.

ClusterRole & ClusterRoleBinding

First, we are going to create a service account

kubectl create serviceaccount bob

Now write the below two YAML files for the ClusterRole & ClusterRoleBinding-

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: bob
rules:
  - apiGroups:
      - ''
    resources:
      - pods
      - pods/status
      - namespace
      - deployments
    verbs:
      - get
      - list
      - watch
      - create
      - update
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: bob-binding
subjects:
  - kind: ServiceAccount
    name: bob
    namespace: default
roleRef:
  kind: ClusterRole
  name: bob
  apiGroup: rbac.authorization.k8s.io

Here we first create a service account and we define a role that will be able to get, list, watch, create, and update the pods, deployments, and namespace.

Later we create a cluster role binding that will map the cluster role to the service account.

Role & RoleBinding

Let’s create a namespace first.

apiVersion: v1
kind: Namespace
metadata:
  name: application
  labels:
    name: alice

Then define the below Role and RoleBinding

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: application
  name: alice
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "watch", "list"]
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: alice-binding
  namespace: application
subjects:
- kind: User
  name: alice
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: alice
  apiGroup: rbac.authorization.k8s.io

Here we create a namespace and then define a role that will allow get, watch, and list operations on the pods to the Alice namespace.

Later we map the role binding to the namespace with role binding.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s