How to Create ServiceAccount, Role, and RoleBinding in Kubernetes
- Last Updated On: February 15, 2024
- By: Aswin Vijayan
In this blog, we are going to see how to create a serviceaccount, role, and rolebinding in Kubernetes.
Create ServiceAccount
First, we are going to create a ServiceAccount on the default namespace, create a YAML file serviceaccount.yaml, and copy the below content to it
apiVersion: v1
kind: ServiceAccount
metadata:
name: kube-service-account
namespace: default
Run the following command to create the ServiceAccount
kubectl apply -f serviceaccount.yaml
This file will create a ServiceAccount kube-service-account on the default namespace.
Create Role
Now, create a Role to attach it to the ServiceAccount, create a YAML file role.yaml, and copy the below content
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: kube-role
namespace: default
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list"]
Run the following command to create a role
kubectl apply -f role.yaml
This file will create a role kube-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: kube-role-binding
subjects:
- kind: ServiceAccount
name: kube-service-account
namespace: default
roleRef:
kind: Role
name: kube-role
apiGroup: rbac.authorization.k8s.io
Run the following to bind the role to the serviceaccount
kubectl apply -f rolebinding.yaml
This will bind the role kube-role to the serviceaccount kube-service-account
Now, check the ServiceAccount by listing the pod and configmap using the serviceaccount.
Run the following command to list pod
kubectl get po --as=system:serviceaccount:default:kube-service-account
The ServiceAccount only has permission to list pod, it cannot list configmap or any other resources, let’s see what happens when we list pod and configmap.
As you can see in the above image, I am able to list pods using ServiceAccount and when I try to list configmap it says the serviceaccount does not have permission to list configmaps.
Aswin Vijayan
Other Interesting Blogs
[40% OFF] Linux Foundation LFCA, LFCS & LFCT Exam Voucher Codes
Linux Foundation has announced up to a $284 discount on its Linux certification programs Linux Foundation Certified IT Associate (LFCA) and Linux
Linux Foundation Coupon for October 2024
Hi Techies, I wanted to let you know about a pretty sweet deal with the Linux Foundation Coupon that is running now.
CKA Certification Study Guide (Certified Kubernetes Administrator)
This comprehensive CKA certification exam study guide covers all the important aspects of the Certified Kubernetes Administrator exam and useful resources. Passing