ServiceAccounts
A ServiceAccount is an identity for processes running in Pods to authenticate to the API server.
While users are people, a ServiceAccount is an identity for the software running inside a Pod. When an app needs to call the Kubernetes API — to list Pods, read a ConfigMap, or create a Job — it does so as a ServiceAccount.
How it works
- Every namespace has a
defaultServiceAccount, used if you don't specify one. - Kubernetes mounts a short-lived token into the Pod automatically.
- You grant the ServiceAccount permissions with RBAC (next lesson).
Best practice
Create a dedicated ServiceAccount per app with the least privileges it needs, rather than reusing the powerful default one.
Example
apiVersion: v1
kind: ServiceAccount
metadata:
name: app-sa
---
apiVersion: v1
kind: Pod
metadata:
name: api-caller
spec:
serviceAccountName: app-sa
containers:
- name: app
image: myapp:1.0When to use it
- A CI/CD pipeline uses a dedicated ServiceAccount with minimal permissions so it can deploy to a namespace without having cluster-admin rights.
- An application pod reads Kubernetes API objects using the automatically mounted ServiceAccount token to watch ConfigMap changes at runtime.
- A team disables auto-mounting of the default ServiceAccount token on pods that do not need API access, reducing the attack surface.
More examples
Create and assign a ServiceAccount
Creates a ServiceAccount named deploy-bot and shows how to reference it in a pod spec.
kubectl create serviceaccount deploy-bot -n production
# Assign to a pod
# spec.serviceAccountName: deploy-botServiceAccount in pod spec
Assigns the deploy-bot ServiceAccount to a CI runner pod so it can authenticate to the Kubernetes API with the SA's token.
apiVersion: v1
kind: Pod
metadata:
name: ci-runner
spec:
serviceAccountName: deploy-bot
automountServiceAccountToken: true
containers:
- name: runner
image: bitnami/kubectl:1.28Disable auto-mount on default SA
Disables automatic token mounting for the default ServiceAccount in a namespace so pods do not get API credentials by default.
kubectl patch serviceaccount default \
-p '{"automountServiceAccountToken": false}'
# Verify
kubectl get serviceaccount default -o yaml | grep automount
Discussion