Skip to content
LF Cert Trainer

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

1/11Service accounts
0:00 / 4:12

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.

Two kinds of identity, one API servercerttokenruns asallowed?Personcertificate or OIDCPodruns as build-botAPI serverwho is calling?ServiceAccountbuild-bot in ns ciRBACRoles and bindings
Two kinds of identity, one API server. People prove who they are with something issued outside the cluster. Programs use a ServiceAccount, which is an ordinary object in a namespace. Both are then checked against the same RBAC rules.

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 accountService account
Meant forPeoplePrograms, inside or outside the cluster
Stored in the clusterNo. There is no User objectYes: kind: ServiceAccount, apiVersion: v1
ScopeThe whole clusterOne namespace
Created byWhoever runs your certificate authority or login systemAnyone allowed to, with kubectl create serviceaccount
Proves itself withClient certificate, OIDC tokenA signed token issued by the API server
Name seen by RBACjanesystem: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 default service 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-bot in ci and build-bot in prod are 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

How a Pod gets its tokencreateplacedTokenRequesttokenmountPod webserviceAccountNameAdmissionadds a token volumekubeletasks for a tokenAPI serversigns a 1 hour tokenProjected volumetoken, ca.crt, nsContainerreads the token file
How a Pod gets its token. Nobody copies a token into the Pod by hand. Admission adds a volume, the kubelet asks the API server for a token bound to this one Pod, and it keeps the file fresh for as long as the Pod lives.

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
  1. You create a Pod. The ServiceAccount admission controller sets spec.serviceAccountName to default if it is empty, checks that the account exists, and adds a volume named kube-api-access-<random> with a mount in every container.
  2. 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.
  3. The API server signs a JSON Web Token and returns it. The kubelet writes it into the volume.
  4. The container finds three files under /var/run/secrets/kubernetes.io/serviceaccount/.
FileContentsUsed for
tokenThe signed token for this PodThe Authorization: Bearer header
ca.crtThe cluster's CA certificate, from the ConfigMap kube-root-ca.crtChecking that the server really is the API server
namespaceThe Pod's namespaceKnowing 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

What the API server does with the tokenHTTPSwhonot validnot allowedallowedApp in the Podsends Bearer tokenAuthenticationsignature, expiryAuthorizationRBAC rules401 Unauthorizedbad or expired token403 Forbiddenno rule matches200 OKa binding allows it
What the API server does with the token. Two separate questions. Authentication asks whether the token is genuine and still valid. Authorization asks whether that identity may do this. A new ServiceAccount passes the first and fails the second.

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

TokenHow you get itLifetimeStoredUse it for
Mounted (projected)Automatic, in every PodAbout 1 hour, rotated by the kubelet, dies with the PodOnly in the Pod's volumePrograms running in the cluster
On requestkubectl create token <name>1 hour by default, --duration to changeNowhere. Printed onceScripts, pipelines, a dashboard login
Legacy SecretA Secret of type kubernetes.io/service-account-token that you createNever expiresIn etcd, readable by anyone who can read the SecretOnly 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 serviceAccountName in the wrong place. It belongs under the Pod's spec, next to containers. In a Deployment that is spec.template.spec, not the top-level spec.
  • 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 -n creates it in default, and the Pod is refused.
  • Binding to the wrong subject. --user=build-bot or --serviceaccount=build-bot without the namespace does not match. The subject is ci:build-bot on the command line, and kind: ServiceAccount with name and namespace in 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-admin to 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: default unless spec.serviceAccountName says 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: false switches 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.