How to Create a ClusterRole and RoleBinding in Kubernetes

In this blog, we are going to see how to create a clusterrole and rolebinding in Kubernetes.

In this example, I am going to create a clusterrole and bind it to a service account.

Create ServiceAccount

First, we are going to create a ServiceAccount on the default namespace, create a YAML file sa.yaml, and copy the below content to it

apiVersion: v1
kind: ServiceAccount
metadata:
  name: cluster-service-account
  namespace: default

Run the following command to create the ServiceAccount

kubectl apply -f sa.yaml

This file will create a ServiceAccount cluster-service-account on the default namespace.

Create ClusterRole

Now, create a ClusterRole to attach it to the ServiceAccount, create a YAML file role.yaml, and copy the below content

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: cluster-role
  namespace: default
rules:
- apiGroups: [""]
  resources: ["nodes"]
  verbs: ["get", "list"]

Run the following command to create a role

kubectl apply -f role.yaml

This file will create a clusterrole cluster-role on the default namespace.

Create RoleBinding

Now, that the ServiceAccount and Role have been created, the next step is to bind the Role to the ServiceAccount.

Create a YAML file rolebinding.yaml and copy the below content

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: cluster-role-binding
subjects:
- kind: ServiceAccount
  name: cluster-service-account
  namespace: default
roleRef:
  kind: Role
  name: cluster-role
  apiGroup: rbac.authorization.k8s.io

Run the following to bind the clusterrole to the serviceaccount

kubectl apply -f rolebinding.yaml 

This will bind the role cluster-role to the serviceaccount cluster-service-account

Conclusion

In Kubernetes, with the help of clusterrole, you can control the access given to a user on the cluster.

I hope this quick guide helps you to set up clusterrole and bind the role to a serviceaccount.

Other Interesting Blogs

Leave a Comment

Share via
Copy link
Powered by Social Snap