ServiceAccounts
Humans authenticate as users; programs running in Pods authenticate as ServiceAccounts. A ServiceAccount is a namespaced object that gives a workload an identity, which RBAC can then grant permissions to. Every namespace has one called default, used by Pods that don't specify another.
apiVersion: v1
kind: ServiceAccount
metadata:
name: pod-reader
namespace: shop
automountServiceAccountToken: false # opt in per Pod instead
---
apiVersion: v1
kind: Pod
metadata:
name: inventory-sync
namespace: shop
spec:
serviceAccountName: pod-reader
automountServiceAccountToken: true
containers:
- name: sync
image: ghcr.io/acme/inventory-sync:1.0Its username in RBAC is system:serviceaccount:<namespace>:<name>, and it belongs to the groups system:serviceaccounts and system:serviceaccounts:<namespace>.
kubectl create serviceaccount pod-reader -n shop
kubectl create rolebinding pod-reader --role=reader --serviceaccount=shop:pod-reader -n shop
kubectl auth can-i list pods -n shop --as=system:serviceaccount:shop:pod-readerTokens
The kubelet mounts a short-lived, automatically rotated projected token into the Pod at /var/run/secrets/kubernetes.io/serviceaccount/:
| File | Content |
|---|---|
token |
A signed JWT, valid ~1 hour, bound to this Pod |
ca.crt |
The cluster CA to verify the API server |
namespace |
The Pod's namespace |
Client libraries find these automatically ("in-cluster config"). The token is a JWT: three base64url parts, a header, a payload with claims, and a signature. We can decode the payload of a sample token (built here, unsigned) to see the claims Kubernetes puts in:
import base64
import json
def b64url(data):
return base64.urlsafe_b64encode(json.dumps(data, separators=(",", ":")).encode()).rstrip(b"=").decode()
header = {"alg": "RS256", "kid": "k8s-2026"}
claims = {
"aud": ["https://kubernetes.default.svc"],
"exp": 1767229200,
"iat": 1767225600,
"iss": "https://kubernetes.default.svc",
"kubernetes.io": {"namespace": "shop", "pod": {"name": "inventory-sync"},
"serviceaccount": {"name": "pod-reader"}},
"sub": "system:serviceaccount:shop:pod-reader",
}
token = f"{b64url(header)}.{b64url(claims)}.signature"
print("token starts:", token[:40] + "...")
payload = token.split(".")[1]
payload += "=" * (-len(payload) % 4) # restore padding
decoded = json.loads(base64.urlsafe_b64decode(payload))
print("subject:", decoded["sub"])
print("audience:", decoded["aud"])
print("valid for:", (decoded["exp"] - decoded["iat"]) // 60, "minutes")
print("bound to pod:", decoded["kubernetes.io"]["pod"]["name"])token starts: eyJhbGciOiJSUzI1NiIsImtpZCI6Ims4cy0yMDI2...
subject: system:serviceaccount:shop:pod-reader
audience: ['https://kubernetes.default.svc']
valid for: 60 minutes
bound to pod: inventory-sync
Note: Before Kubernetes 1.24, each ServiceAccount got a long-lived token in a Secret that never expired. Those are no longer created automatically. If you need a token outside a Pod (for a CI system), use
kubectl create token pod-reader --duration=1h.
Calling the API from a Pod
An app in the cluster calls https://kubernetes.default.svc with the token as a bearer header. With the official Python client this is one line (config.load_incluster_config()). Under the hood, it's just HTTP:
TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)
curl --cacert /var/run/secrets/kubernetes.io/serviceaccount/ca.crt \
-H "Authorization: Bearer $TOKEN" \
https://kubernetes.default.svc/api/v1/namespaces/shop/podsSample output (when the ServiceAccount lacks permission):
{
"kind": "Status",
"status": "Failure",
"message": "pods is forbidden: User \"system:serviceaccount:shop:pod-reader\" cannot list resource \"pods\" in API group \"\" in the namespace \"shop\"",
"reason": "Forbidden",
"code": 403
}The message format is predictable, so let's model how the API server builds it from the request:
def forbidden(sa_ns, sa_name, verb, resource, group, namespace):
user = f"system:serviceaccount:{sa_ns}:{sa_name}"
scope = f' in the namespace "{namespace}"' if namespace else " at the cluster scope"
return (f'{resource} is forbidden: User "{user}" cannot {verb} resource "{resource}" '
f'in API group "{group}"{scope}')
print(forbidden("shop", "pod-reader", "list", "pods", "", "shop"))
print(forbidden("shop", "default", "list", "nodes", "", None))pods is forbidden: User "system:serviceaccount:shop:pod-reader" cannot list resource "pods" in API group "" in the namespace "shop"
nodes is forbidden: User "system:serviceaccount:shop:default" cannot list resource "nodes" in API group "" at the cluster scope
Workload identity in the cloud
Cloud providers can trust ServiceAccount tokens to hand out cloud credentials, so Pods never need static cloud keys:
| Cloud | Feature | Link |
|---|---|---|
| AWS EKS | IRSA / EKS Pod Identity | Annotation eks.amazonaws.com/role-arn on the ServiceAccount |
| GKE | Workload Identity Federation | IAM binding to PROJECT.svc.id.goog[ns/sa] |
| AKS | Microsoft Entra Workload ID | Annotation azure.workload.identity/client-id |
Good practices
- Create one ServiceAccount per application, never grant permissions to
default. - Set
automountServiceAccountToken: falsefor apps that never call the Kubernetes API (most of them), so a compromised container has no token to steal. - Bind only the verbs/resources the app needs (see RBAC).
Test yourself
What is the RBAC username of ServiceAccount ci in namespace tools?
- ci
- tools:ci
- system:serviceaccount:tools:ci
- serviceaccount/ci
Which ServiceAccount does a Pod use if serviceAccountName is not set?
- None
- admin
- default (in the Pod's namespace)
- kube-system
Why set automountServiceAccountToken: false?
- To make Pods start faster
- So workloads that don't call the API have no token to leak
- It is required for Deployments
- To disable DNS