role vs rolebinding in kubernetes

You need to know the difference between

  • Role.
  • Rolebinding.
  • ClusterRole.

Please refer the Kubernetes documentation here

A Role always sets permissions within a particular namespace; when you create a Role, you have to specify the namespace it belongs in.

ClusterRole, by contrast, is a non-namespaced resource. The resources have different names (Role and ClusterRole) because a Kubernetes object always has to be either namespaced or not namespaced; it can’t be both.

A rolebinding is namespace scoped and clusterrolebinding is cluster scoped i.e across all namespace.

ClusterRoles and ClusterRoleBindings are useful in the following cases:

  1. Give permissions for non-namespaced resources like nodes
  2. Give permissions for resources in all the namespaces of a cluster
  3. Give permissions for non-resource endpoints like /healthz

A RoleBinding can also reference a ClusterRole to grant the permissions defined in that ClusterRole to resources inside the RoleBinding’s namespace. This kind of reference lets you define a set of common roles across your cluster, then reuse them within multiple namespaces.

example

Create a Role for the dev User

  1. Create a role spec file role.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: beebox-mobile
  name: pod-reader
rules:
- apiGroups: [""]
  resources: ["pods", "pods/log"]
  verbs: ["get", "watch", "list"]

2. Save and exit the file by pressing Escape followed by :wq.

3. apply the role.

kubectl apply -f file-name.yml

Bind the Role to the dev User and Verify Your Setup Works

  1. Create the RoleBinding spec file:
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: pod-reader
  namespace: beebox-mobile
subjects:
- kind: User
  name: dev
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: pod-reader
  apiGroup: rbac.authorization.k8s.io

2. Apply the role, by running

kubectl apply -f file-name.yml

Cheers

Osama

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.