Kubernetes CKS sample exam question 1 with answer - ServiceAccount, Role, RoleBinding

Question

Create a new ServiceAccount named backend-sa in the existing namespace default, which has the capability to list the pods inside the namespace default.

Create a new Pod named backend-pod in the namespace default, mount the newly created ServiceAccount backend-sa to the Pod, and verify that the pod is able to list pods.

Ensure that the Pod is running

Answer

First, create ServiceAccount backend-sa:

kubectl create sa backend-sa
Create a Role named backend-role which have capability to list pods:
kubectl create role backend-role --resource=pods --verb list
Create a RoleBinding which binds above role with ServiceAccount:
kubectl create rolebinding backend-rb --role backend-role --serviceaccount default:backend-sa
Verify if ServiceAccount has rights to list pods. You should get yes:
kubectl auth can-i list pods --as system:serviceaccount:default:backend-sa
Let's create the Pod. Generate manifest file:
kubectl run backend-pod --image=nginx -o yaml --dry-run=client > pod.yaml
Edit the pod and add ServiceAccountName entry, so it will match like this:
apiVersion: v1
kind: Pod
metadata:
  labels:
    run: backend-pod
  name: backend-pod
spec:
  serviceAccountName: backend-sa
  containers:
  - image: nginx
    name: backend-pod
Create the pod:
kubectl apply -f pod.yaml
Describe it and check if ServiceAccount is mounted:
kubectl describe pod backend-pod
You should have something like this:
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-762l2 (ro)
Exec into the Pod:
kubectl exec -it  backend-pod -- bash
And try to curl the Kubernetes API using mounted token in the /var/run/secrets/kubernetes.io/serviceaccount:
curl -s -k -m 5 -H "Authorization: Bearer $(cat /var/run/secrets/kubernetes.io/serviceaccount/token)" https://kubernetes.default.svc.cluster.local/api/v1/namespaces/default/pods
You should get a list of Pods.