Lesson 83 · Section 7: Security
Lesson 83: Service accounts: an identity for Pods and other programs
How a program proves who it is to the API server: the ServiceAccount object, the short-lived token the kubelet mounts into every Pod, how RBAC gives that identity permissions, and the exam routine for creating an account, attaching it to a workload and testing what it may do. · 18 min read · 4 min video
Official competencies this lesson covers
Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.
Why service accounts exist
So far in this section, the caller of the API has been a person: someone with a client certificate in a kubeconfig
file. But most requests to a real API server do not come from people. They come from programs: the controllers in
kube-system, an ingress controller watching for new Ingress objects, a monitoring agent listing Pods, a CI
pipeline deploying a new image.
Those programs need an identity too, and a person's certificate is the wrong tool. It is valid for a year, it cannot be revoked easily, and it would have to be copied into every Pod by hand. Kubernetes solves this with a second kind of identity that the cluster itself manages.
Parts:
- Person (certificate or OIDC)
- Pod (runs as build-bot)
- API server (who is calling?)
- ServiceAccount (build-bot in ns ci)
- RBAC (Roles and bindings)
Connections:
- Person to API server: cert
- Pod to API server: token
- Pod to ServiceAccount: runs as
- API server to RBAC: allowed?
What a service account is
| User account | Service account | |
|---|---|---|
| Meant for | People | Programs, inside or outside the cluster |
| Stored in the cluster | No. There is no User object | Yes: kind: ServiceAccount, apiVersion: v1 |
| Scope | The whole cluster | One namespace |
| Created by | Whoever runs your certificate authority or login system | Anyone allowed to, with kubectl create serviceaccount |
| Proves itself with | Client certificate, OIDC token | A signed token issued by the API server |
| Name seen by RBAC | jane | system:serviceaccount:<namespace>:<name> |
The object itself is almost empty. It is a name that tokens can be issued for and that RBAC can refer to:
apiVersion: v1
kind: ServiceAccount
metadata:
name: build-bot
namespace: ci
Three facts about it come up again and again:
- Every namespace has a
defaultservice account. A controller creates it as soon as the namespace exists, and recreates it if you delete it. - Every Pod runs as exactly one service account. If the Pod spec names none, admission fills in
default. - The full user name includes the namespace.
build-botinciandbuild-botinprodare two different identities with different permissions.
Each service account also belongs to two groups, which lets a single binding cover many accounts:
system:serviceaccounts:<namespace> (every account in that namespace) and system:serviceaccounts (every account
in the cluster).
How it works
From the Pod spec to a token file
Parts:
- Pod web (serviceAccountName)
- Admission (adds a token volume)
- kubelet (asks for a token)
- API server (signs a 1 hour token)
- Projected volume (token, ca.crt, ns)
- Container (reads the token file)
Connections:
- Pod web to Admission: create
- Admission to kubelet: placed
- kubelet to API server: TokenRequest
- API server to Projected volume: token
- Projected volume to Container: mount
- You create a Pod. The ServiceAccount admission controller sets
spec.serviceAccountNametodefaultif it is empty, checks that the account exists, and adds a volume namedkube-api-access-<random>with a mount in every container. - The scheduler places the Pod. The kubelet on that node calls the TokenRequest API and asks for a token for this account, bound to this Pod.
- The API server signs a JSON Web Token and returns it. The kubelet writes it into the volume.
- The container finds three files under
/var/run/secrets/kubernetes.io/serviceaccount/.
| File | Contents | Used for |
|---|---|---|
token | The signed token for this Pod | The Authorization: Bearer header |
ca.crt | The cluster's CA certificate, from the ConfigMap kube-root-ca.crt | Checking that the server really is the API server |
namespace | The Pod's namespace | Knowing where "here" is |
You can see the volume on any running Pod:
volumes:
- name: kube-api-access-x7k2p
projected:
sources:
- serviceAccountToken:
expirationSeconds: 3607
path: token
- configMap:
name: kube-root-ca.crt
items:
- { key: ca.crt, path: ca.crt }
- downwardAPI:
items:
- path: namespace
fieldRef: { fieldPath: metadata.namespace }
Client libraries and kubectl look in that folder automatically when they run inside a Pod, and they find the API
server through the kubernetes Service in the default namespace. That is why a controller needs no kubeconfig.
Why the token is short-lived and bound
The mounted token is called a bound service account token. It has three limits built in:
- Time. It is valid for about an hour. The kubelet fetches a new one when the old one has used 80% of its lifetime and swaps the file. Applications should re-read the file from time to time rather than keep the token in memory for ever.
- Object. It is tied to one Pod. Delete the Pod and the token stops working at once, even if its hour is not over.
- Audience. It names who it is for, by default the API server. A token minted for another audience is refused.
This matters because a token is a password. If one leaks from a log file or a compromised container, the damage ends when the Pod does.
Under the hood · What is inside the token
The token is three base64 parts separated by dots: header, payload and signature. The payload of a mounted token looks like this:
{
"aud": ["https://kubernetes.default.svc.cluster.local"],
"exp": 1796040000,
"iss": "https://kubernetes.default.svc.cluster.local",
"kubernetes.io": {
"namespace": "ci",
"pod": { "name": "web", "uid": "0f3c9a1e-6f0e-4a5b-9a35-0c1e6d4d2b11" },
"serviceaccount": { "name": "build-bot", "uid": "6c2d8e55-2d5f-4a0f-8f6a-3b6f3a7b9c42" }
},
"sub": "system:serviceaccount:ci:build-bot"
}
sub is the user name RBAC sees. The API server checks the signature with its own key
(--service-account-key-file), then checks exp, and then checks that the Pod and the ServiceAccount named inside
still exist with the same UIDs. Deleting and recreating a service account with the same name therefore invalidates
every old token.
Authenticated is not the same as allowed
Parts:
- App in the Pod (sends Bearer token)
- Authentication (signature, expiry)
- Authorization (RBAC rules)
- 401 Unauthorized (bad or expired token)
- 403 Forbidden (no rule matches)
- 200 OK (a binding allows it)
Connections:
- App in the Pod to Authentication: HTTPS
- Authentication to Authorization: who
- Authentication to 401 Unauthorized: not valid
- Authorization to 403 Forbidden: not allowed
- Authorization to 200 OK: allowed
A token only answers "who is this?". What the caller may do is a separate decision, made by RBAC, and a new service account has no permissions of its own. It can reach a few discovery endpoints that every authenticated caller may read, and nothing else:
Error from server (Forbidden): pods is forbidden: User "system:serviceaccount:ci:build-bot"
cannot list resource "pods" in API group "" in the namespace "ci"
That message is worth reading closely, because it gives you the exact user name to put in a binding. You grant
access with the Roles and bindings from the RBAC lessons, using a subject of kind: ServiceAccount:
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: build-bot-reads
namespace: ci
subjects:
- kind: ServiceAccount
name: build-bot
namespace: ci # required for a ServiceAccount subject
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: pod-reader
Three kinds of token
| Token | How you get it | Lifetime | Stored | Use it for |
|---|---|---|---|---|
| Mounted (projected) | Automatic, in every Pod | About 1 hour, rotated by the kubelet, dies with the Pod | Only in the Pod's volume | Programs running in the cluster |
| On request | kubectl create token <name> | 1 hour by default, --duration to change | Nowhere. Printed once | Scripts, pipelines, a dashboard login |
| Legacy Secret | A Secret of type kubernetes.io/service-account-token that you create | Never expires | In etcd, readable by anyone who can read the Secret | Only when a tool cannot refresh a token |
Using it
Example · Create an account and run a workload as it
The task: the Deployment web in namespace ci must run as a new service account build-bot.
kubectl create serviceaccount build-bot -n ci
kubectl set serviceaccount deployment/web build-bot -n ci
kubectl rollout status deployment/web -n ci
kubectl set serviceaccount writes serviceAccountName into the Pod template, which starts a rolling update.
The same change by hand, with kubectl edit deployment web -n ci:
spec:
template:
spec:
serviceAccountName: build-bot # under the template's spec, not the Deployment's
containers:
- name: web
image: nginx:1.29-alpine
Check a Pod, not only the Deployment:
kubectl get pods -n ci -o custom-columns=NAME:.metadata.name,SA:.spec.serviceAccountName
NAME SA
web-6b7f9c8d5d-4xk2p build-bot
web-6b7f9c8d5d-qz8mw build-bot
For a single Pod, kubectl run has no flag for the account. Generate the YAML with
kubectl run web --image=nginx:1.29-alpine --dry-run=client -o yaml and add the serviceAccountName line.
Example · Give the account permissions and prove they work
The task: build-bot may read Pods in ci, and nothing more.
kubectl create role pod-reader -n ci --verb=get,list,watch --resource=pods
kubectl create rolebinding build-bot-reads -n ci --role=pod-reader --serviceaccount=ci:build-bot
The --serviceaccount flag always takes <namespace>:<name>. Now test as the account. No Pod and no token are
needed, because --as makes the API server evaluate the rules for another identity:
kubectl auth can-i list pods -n ci --as=system:serviceaccount:ci:build-bot # yes
kubectl auth can-i delete pods -n ci --as=system:serviceaccount:ci:build-bot # no
kubectl auth can-i list pods -n default --as=system:serviceaccount:ci:build-bot # no: the Role is in ci
kubectl auth can-i --list -n ci --as=system:serviceaccount:ci:build-bot # everything it may do
Example · Call the API from inside a Pod
This is what every client library does for you. Doing it once by hand makes the three files concrete.
kubectl run probe -n ci --image=curlimages/curl:8.11.1 \
--overrides='{"spec":{"serviceAccountName":"build-bot"}}' --command -- sleep 3600
kubectl exec -it probe -n ci -- sh
Inside the container:
SA=/var/run/secrets/kubernetes.io/serviceaccount
NS=$(cat $SA/namespace)
curl --cacert $SA/ca.crt -H "Authorization: Bearer $(cat $SA/token)" \
https://kubernetes.default.svc/api/v1/namespaces/$NS/pods
With the binding from the previous example you get a JSON PodList. Ask for /secrets instead of /pods and
you get 403 Forbidden with the account's full name in the message. Send no header at all and the request is
treated as system:anonymous.
Example · Get a token for something outside the cluster
A pipeline or a dashboard needs a token it can paste into a login form or a kubeconfig.
kubectl create token build-bot -n ci # valid 1 hour
kubectl create token build-bot -n ci --duration=8h # the server may cap the duration
The token is printed and not saved. To use it from your own terminal:
TOKEN=$(kubectl create token build-bot -n ci)
kubectl --token="$TOKEN" get pods -n ci # acts as build-bot
kubectl --token="$TOKEN" auth whoami # shows the user name and groups
Only if a tool cannot handle expiry, create the permanent kind yourself. The control plane fills in the token:
apiVersion: v1
kind: Secret
metadata:
name: build-bot-token
namespace: ci
annotations:
kubernetes.io/service-account.name: build-bot
type: kubernetes.io/service-account-token
kubectl get secret build-bot-token -n ci -o jsonpath='{.data.token}' | base64 -d
Deleting the Secret revokes that token. Deleting the service account revokes all of its tokens.
Example · Turn the token off for a Pod that never calls the API
Most applications never talk to the API server. A token they do not need is only something to steal. Switch the mount off on the account, for every Pod that uses it:
apiVersion: v1
kind: ServiceAccount
metadata:
name: web
namespace: ci
automountServiceAccountToken: false
or on one Pod:
spec:
serviceAccountName: web
automountServiceAccountToken: false
When both are set, the Pod's value wins. Check the result:
kubectl exec web -n ci -- ls /var/run/secrets/kubernetes.io/serviceaccount
# ls: /var/run/secrets/kubernetes.io/serviceaccount: No such file or directory
The Pod still has a service account. It just carries no proof of it.
Tricks
Common mistakes
- Putting
serviceAccountNamein the wrong place. It belongs under the Pod'sspec, next tocontainers. In a Deployment that isspec.template.spec, not the top-levelspec. - Trying to change the account on a running Pod. The field cannot be edited. Change the Deployment so new Pods are created, or delete and recreate a bare Pod.
- Creating the account in the wrong namespace. A Pod can only use an account from its own namespace. Forgetting
-ncreates it indefault, and the Pod is refused. - Binding to the wrong subject.
--user=build-botor--serviceaccount=build-botwithout the namespace does not match. The subject isci:build-boton the command line, andkind: ServiceAccountwithnameandnamespacein YAML. - Expecting a new account to be able to do something. Creating it grants nothing. Without a binding, every
real request ends in
403 Forbidden. - Looking for the token in a Secret. On a current cluster there is none. Use
kubectl create token, or read the file inside the Pod. - Binding
cluster-adminto make an error go away. It works, and it hands the whole cluster to anything that can read that Pod's token. Grant the verbs and resources from the error message instead.
Recap
- A ServiceAccount is a namespaced identity for programs. RBAC sees it as
system:serviceaccount:<namespace>:<name>. - Every Pod runs as one account:
defaultunlessspec.serviceAccountNamesays otherwise. The field is fixed once the Pod exists. - The kubelet mounts a token at
/var/run/secrets/kubernetes.io/serviceaccount/, valid about an hour, bound to the Pod and rotated automatically.automountServiceAccountToken: falseswitches it off. - An account has no permissions until a RoleBinding or ClusterRoleBinding names it. Test with
kubectl auth can-i ... --as=system:serviceaccount:<ns>:<name>. - For use outside a Pod,
kubectl create token <name>prints a short-lived token. Permanent Secret tokens are no longer created automatically.
Official docs
Quiz: check what you learned
5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.
Sign in to take the quiz and keep your score.
Practise: try it on a real cluster
2 hands-on labs for this lesson. You get goals, not steps: any solution that reaches them passes.
Give an app its own service account with just the access it needs, and take the API token away from an app that never calls the API.
Build · Level 2 · standard · target 20 min
Section capstone. Prepare a namespace for an audit: a short-lived login for the auditor, read-only access for her group, an identity of its own for one app, a hardened container, and network policies that close the namespace.
Build · Level 3 · challenge · target 40 min
Discussion
Learners ask and answer questions here. Sign in to read and join the discussion.