Kubernetes RBAC: How to Create Cluster Roles and Bindings?

In this blog, we are going to look at how we can create Cluster Role objects and how we can attach them to a Cluster Role Binding object.

If you don’t know which object is Cluster scoped or which one is Namespace scoped, use the following command to list them.

kubectl api-resources
api resources

In this list, if NAMESPCED is true then it is Namespace scoped, if false, those are cluster scoped.

Step 1: Create a Service Account

We need to create a Service to attach the Cluster Role.

cat << EOF > pv-list-serviceaccount.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: pv-list-service-account
EOF
kubectl apply -f pv-list-serviceaccount.yaml

Step 2: Create a Cluster Role

Cluster Role is almost the same as Role object, here also under the rules section, we provide API groups, Resources as well as verbs which is permission.

cat << EOF > pv-list-clusterrole.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: pv-lister
rules:
- apiGroups: [""]
  resources: ["persistentvolumes"]
  verbs: ["list"]
EOF

In this manifest, we are providing permission to only list the Persistent Volumes on the cluster and PVs are cluster-scoped objects.

kubectl apply -f pv-list-clusterrole.yaml

Step 3: Create a Cluster Role Binding

Now, we need to create a Cluster Role Binding object to link the Service Account with the Cluster Role.

cat << EOF > pv-list-clusterrolebinding.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: pv-list-clusterrole-binding
subjects:
- kind: ServiceAccount
  name: pv-list-service-account
  namespace: default
roleRef:
  kind: ClusterRole
  name: pv-lister
  apiGroup: rbac.authorization.k8s.io
EOF
kubectl apply -f pv-list-clusterrolebinding.yaml

We can test that the permissions are properly assigned to the Service Account. For that first, we can try to get the list of Persistent Volumes on the cluster.

kubectl get pv --as=system:serviceaccount:default:pv-list-service-account
list of persistent volume

The permission is properly working, the Service Account can able to list the Persistent Volumes.

We haven’t given permission to access any other Cluster scoped objects so let’s check that too.

kubectl get nodes --as=system:serviceaccount:default:pv-list-service-accou
nt
RBAC permission error

Here, we are facing an error and the error indicates that the Service Account doesn’t have permission to do this operation.

Conclusion

Role Based Access Control is one of the command Authorization mechanisms on Kubernetes and knowing about the creation of this configuration will help you to do your day-to-day tasks on Kubernetes as well as help for your certification exam preparation.

0 Shares:
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like