k8s rbac role, rolebinding and testing

In AKS we can setup rbac for service acount. Let's create a service account and then  using the following yaml definition to setup it access to list pods. 


kubectl create serviceaccount pod-watcher -n dev

Next we will create a role that only allows this service account to list and watch pods in dev namespace, Role is reusable. 


apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: dev
  name: pod-reader-only
rules:
- apiGroups: [""] # The core API group
  resources: ["pods"]
  verbs: ["get", "list", "watch"] # No "delete", "create", or "update"


Here we can see the common apiGroups that you can use and please ensure you do not omit the (s) - plural as will NOT work

API GroupCommon Resources
"" (Core)pods, services, nodes, namespaces, configmaps, secrets, persistentvolumeclaims
appsdeployments, statefulsets, daemonsets, replicasets
batchjobs, cronjobs
networking.k8s.ioingresses, networkpolicies
autoscalinghorizontalpodautoscalers
storage.k8s.iostorageclasses, csinodes

for example, if we would like to specifiy that it can list cronjob, it will be like this 

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: dev
  name: pod-reader-cronjob-only
rules:
- apiGroups: ["batch"] # The batch API group
  resources: ["cronjobs"] # Plural here !!
  verbs: ["get", "list", "watch"] # No "delete", "create", or "update"

Next we will tied the user to the role using rolebinding as shown here. Please note, rolebinding won't check if the "roleRef" target let's say group exist or not. 

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: read-pods-binding
  namespace: dev
subjects:
- kind: ServiceAccount
  name: pod-watcher
  namespace: dev
roleRef:
  kind: Role
  name: pod-reader-only
  apiGroup: rbac.authorization.k8s.io

And to test it out we can use kubectl auth can-i command


# YES
kubectl auth can-i list pods --as system:serviceaccount:dev:pod-watcher  -n dev
# NO
kubectl auth can-i delete pods --as system:serviceaccount:dev:pod-watcher   -n dev

# YES

kubectl auth can-i list cronjob --as system:serviceaccount:dev:pod-watcher  -n dev

# NO 

kubectl auth can-i delete cronjob --as system:serviceaccount:dev:pod-watcher  -n dev












Comments

Popular posts from this blog

vllm : Failed to infer device type

NodeJS: Error: spawn EINVAL in window for node version 20.20 and 18.20

android studio kotlin source is null error