How to Create ServiceAccount, Role, and RoleBinding in Kubernetes

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.

ServiceAccount, Role, and RoleBinding: Testing serviceaccount permissions

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.

Other Interesting Blogs

Leave a Comment

Share via
Copy link
Powered by Social Snap