Certified Kubernetes Administrator (CKA) Exam notes – Default Service Account in the pod

Every Kubernetes namespace contains at least one ServiceAccount: the default ServiceAccount for that namespace, named default. If you do not specify a ServiceAccount when you create a Pod, Kubernetes automatically assigns the ServiceAccount named default in that namespace.

Let’s examine the default service account

Create a pod name nginx and run the command ‘kubectl get pods nginx -o yaml | grep -i serviceAccontName’. A service account named ‘default’ will be displayed

Kubernetes mounts a default service account to each pod if the pod doesn’t specify any service account in the manifest. Below is the mount path in the pod

But can pod access Kubernetes API using the default service account. Let’s examine it. Login to the pod and run the below commands

#Login to the pod

Kubectl exec -it nginx /bin/sh

# Point to the internal API server hostname
APISERVER=https://kubernetes.default.svc

# Path to ServiceAccount token
SERVICEACCOUNT=/var/run/secrets/kubernetes.io/serviceaccount

# Read this Pod's namespace
NAMESPACE=$(cat ${SERVICEACCOUNT}/namespace)

# Read the ServiceAccount bearer token
TOKEN=$(cat ${SERVICEACCOUNT}/token)

# Reference the internal certificate authority (CA)
CACERT=${SERVICEACCOUNT}/ca.crt

# Explore the API with TOKEN
curl --cacert ${CACERT} --header "Authorization: Bearer ${TOKEN}" -X GET ${APISERVER}/api

The output will be something like this

All good we can reach the API server using the service account

Let’s see if we can actually do something in the API server. Run the curl to list the pods in the default namespace.

curl –cacert ${CACERT} –header “Authorization: Bearer ${TOKEN}” -X GET ${APISERVER}/api/v1/namespaces/default/pods

Looks like the default service account doesn’t have any role defined. It is not allowed to list pods.

Let’s assign a role to the default service account to list pods and then try the same command again.

Create role and role binding. Note: –serviceaccount format in rolebinding is <namespace>:<service account name>

Create a role: controlplane $ kubectl create role default-sa-role –verb=list –resource=pod

Create role binding: kubectl create rolebinding default-sa-rolebinding –role=default-sa-role –serviceaccount=default:default

Now that we have assigned a role to the default service account it can list the pods. Let’s try the above curl command again.

Note: We don’t need to use the default service account. We can define our own service account in the

References:

https://kubernetes.io/docs/tasks/run-application/access-api-from-pod/