CKAD — ServiceAccounts

less than 1 minute read

ServiceAccounts

Every Pod in Kubernetes runs with a ServiceAccount. The ServiceAccount determines what the Pod can do when calling the Kubernetes API.

Default ServiceAccount

Every namespace has a default ServiceAccount. If you do not specify one, your Pod uses it.

# List ServiceAccounts
kubectl get serviceaccounts
# Expected:
# NAME      SECRETS   AGE
# default   0         30d

# Check which ServiceAccount a Pod uses
kubectl get pod my-pod -o jsonpath='{.spec.serviceAccountName}'
# Expected: default

Creating a ServiceAccount

# Imperative
kubectl create serviceaccount app-sa

# Declarative
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: ServiceAccount
metadata:
  name: app-sa
  namespace: default
automountServiceAccountToken: false
EOF

Assigning a ServiceAccount to a Pod

apiVersion: v1
kind: Pod
metadata:
  name: api-pod
spec:
  serviceAccountName: app-sa
  automountServiceAccountToken: true
  containers:
  - name: app
    image: nginx:1.27
# Verify the token is mounted
kubectl exec api-pod -- ls /var/run/secrets/kubernetes.io/serviceaccount/
# Expected: ca.crt  namespace  token

# Check the token
kubectl exec api-pod -- cat /var/run/secrets/kubernetes.io/serviceaccount/token

Disabling Token Auto-Mount

For Pods that do not need to call the Kubernetes API, disable the token mount for security:

apiVersion: v1
kind: Pod
metadata:
  name: web
spec:
  serviceAccountName: app-sa
  automountServiceAccountToken: false
  containers:
  - name: web
    image: nginx:1.27

Next: RBAC for ServiceAccounts →

Updated: