Skip to content
Français
Account: not signed in, sync available My learning
Select theme
Français

ServiceAccounts for developers

By updated

Improve this page

Logo Kubernetes

A ServiceAccount is the Kubernetes identity of a workload. When a Pod calls the Kubernetes API, the API recognizes it thanks to a token mounted in its container, and this token designates a ServiceAccount. The rights of this identity come from RBAC, which the previous lesson taught. This lesson shows how to give a Pod an identity of its own, what its token contains and how long it is valid, how to list Pods from a Pod, and how to remove the token from a Pod that does not need one. It also teaches you to read a denial from the API to know whether RBAC or admission pronounced it.

What you will learn

  • Associate a dedicated ServiceAccount with a Pod using serviceAccountName
  • Read the projected token of a Pod: where it is mounted, what it contains, how long it lasts
  • Call the API from a Pod with its own token
  • Cut the token mount when the application does not call the API
  • Tell an RBAC denial from an admission denial

Prerequisites

The lesson Kubernetes RBAC carries all the syntax of Roles and RoleBindings, which this page uses without explaining it again. You also need a working cluster and kubectl, as in the previous lessons. Decoding the token, further down, assumes a bash shell and python3 on your workstation.

What is a ServiceAccount for, and what does the default account do?

A ServiceAccount is a Kubernetes object attached to a namespace: two ServiceAccounts with the same name in two namespaces are two different identities. When it is created, it has no rights on the application's resources: no Pods, no Secrets, nothing else. It only receives the basic rights common to every account, which the RBAC lesson listed (the selfsubject* entries, API discovery). RBAC then grants it permissions on the rest.

Each namespace contains a ServiceAccount named default. A Pod that declares nothing receives this account. The default account is not dangerous in itself, but all the Pods of the namespace that use it share the same identity. A RoleBinding placed on default then applies at once to all these Pods, and the audit logs can no longer tell the applications apart.

The rule is therefore simple: one ServiceAccount per application, or per group of applications that have exactly the same needs. Adopt a naming convention from the first one, for example <app>-sa, so that you can easily read who may do what in kubectl get rolebindings -o wide.

The demonstration below creates the equipe namespace and the lecteur ServiceAccount with kubectl create serviceaccount lecteur -n equipe.

How do you associate a ServiceAccount with a Pod?

The serviceAccountName field is declared in the Pod specification. On a Deployment, it goes in spec.template.spec, not under the spec of the Deployment: misplaced, it makes applying the manifest fail.

deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: client-api
namespace: equipe
spec:
replicas: 1
selector:
matchLabels:
app: client-api
template:
metadata:
labels:
app: client-api
spec:
serviceAccountName: lecteur
containers:
- name: curl
image: curlimages/curl:8.23.0@sha256:3fb7e13e5d179a845c97d78204f3f1064d1907037f26a3ebf91710571151fd93
command: ["sleep", "3600"]

The identity of an existing Pod cannot be changed. The API refuses the change and lists the few fields that can be modified: the images of the containers and of the init containers, activeDeadlineSeconds, terminationGracePeriodSeconds, the tolerations (additions only) and the schedulingGates. Resources go through the resize subresource. To change the serviceAccountName, you must recreate the Pod, and therefore modify the Deployment that manages it.

What does the token mounted in a Pod contain?

When a Pod starts, Kubernetes mounts a projected volume named kube-api-access-<suffix> in it. It gathers three files: the token, the certificate of the cluster authority and the namespace of the Pod. The client-api Pod is created in step 2 of the demonstration below: run the two commands that follow after that step. In this Pod, automountServiceAccountToken is absent from the specification, so true by default, and the volume asks for a token of 3607 seconds:

Terminal window
kubectl get pod client-api -n equipe -o jsonpath='automount={.spec.automountServiceAccountToken} serviceAccountName={.spec.serviceAccountName}{"\n"}{.spec.volumes[0]}{"\n"}'
Output
automount= serviceAccountName=lecteur
{"name":"kube-api-access-9p98w","projected":{"defaultMode":420,"sources":[{"serviceAccountToken":{"expirationSeconds":3607,"path":"token"}},{"configMap":{"items":[{"key":"ca.crt","path":"ca.crt"}],"name":"kube-root-ca.crt"}},{"downwardAPI":{"items":[{"fieldRef":{"apiVersion":"v1","fieldPath":"metadata.namespace"},"path":"namespace"}]}}]}}

Look at the serviceAccountToken source and its expirationSeconds: 3607. The token is a projected token: it is bound to the Pod, and is not a permanent token stored in a Secret. In the container, it appears in /var/run/secrets/kubernetes.io/serviceaccount/.

Terminal window
kubectl exec client-api -n equipe -- ls -l /var/run/secrets/kubernetes.io/serviceaccount/
Output
total 0
lrwxrwxrwx 1 root root 13 Nov 12 19:24 ca.crt -> ..data/ca.crt
lrwxrwxrwx 1 root root 16 Nov 12 19:24 namespace -> ..data/namespace
lrwxrwxrwx 1 root root 12 Nov 12 19:24 token -> ..data/token

What does the token contain?

The token is a JWT: three pieces separated by dots, the second of which, the payload, is encoded JSON. This encoding is base64url, without the final = padding. base64 -d alone therefore often fails on this piece. You have to replace - and _ with + and /, then add the missing padding.

The measurement below was made on a second Pod, named jeton, in an equipe2 namespace. It uses a ServiceAccount also named lecteur, but created in equipe2: it is a different identity from the one in equipe. To reproduce the measurement with client-api, replace jeton with client-api and equipe2 with equipe.

Terminal window
P=$(kubectl exec jeton -n equipe2 -- cat /var/run/secrets/kubernetes.io/serviceaccount/token | cut -d. -f2 | tr '_-' '/+')
while [ $(( ${#P} % 4 )) -ne 0 ]; do P="$P="; done
echo "$P" | base64 -d | python3 -m json.tool
Output
{
"aud": [
"https://kubernetes.default.svc.cluster.local"
],
"exp": 1826047587,
"iat": 1794511587,
"iss": "https://kubernetes.default.svc.cluster.local",
"jti": "57e93780-3ba8-489c-87cc-0a26d9c00950",
"kubernetes.io": {
"namespace": "equipe2",
"node": {
"name": "demo-m89-multi-worker2",
"uid": "94f2a550-0e44-4389-9814-7223607a5828"
},
"pod": {
"name": "jeton",
"uid": "25f1325c-8d6e-4a14-8f2f-c708d67b452a"
},
"serviceaccount": {
"name": "lecteur",
"uid": "dd09a074-1c6d-4341-8bbc-92bc0478877e"
},
"warnafter": 1794515194
},
"nbf": 1794511587,
"sub": "system:serviceaccount:equipe2:lecteur"
}

Three groups of fields can be read in this output. sub gives the identity: system:serviceaccount:<namespace>:<name>. aud and iss give the audience, that is, the recipient of the token (here the API server), and the issuer. The kubernetes.io block binds the token to the namespace, the ServiceAccount, the Pod and the node. The API server checks these links: a token presented after the deletion of its Pod is refused.

How long is the token really valid?

The volume asks for 3607 seconds, but the token carries a much more distant expiration: exp minus iat is 1826047587 minus 1794511587, that is 31,536,000 seconds, so 365 days. In the same output, warnafter equals iat plus 3607 seconds, one hour later.

This gap is intended. The API server is started with --service-account-extend-token-expiration, true by default: it extends to one year the expiration of the tokens that admission injects into Pods, so as not to break an application whose token would not be renewed. There is nothing to configure, on kind as on kubeadm: on kind, the option does not even appear in the API server manifest, its default value applies.

The kubelet, for its part, renews the file before the end of the requested hour, and warnafter marks the moment from which the API server flags the use of a token that should have been renewed.

The token read in the file therefore changes by itself, and it is only valid for this Pod, as long as it exists. This does not prevent you from cutting the mount when it is useless, as the section on mounting the token shows further down.

And the token created with kubectl create token?

kubectl create token makes a token that is bound to no Pod, for a test or a one-off integration. Its default duration is one hour, and its audience is that of the API server. The --duration option lengthens it.

Terminal window
kubectl create token lecteur -n equipe
kubectl create token lecteur -n equipe --duration=24h

This token does not renew itself. Storing it in a file, a long-lived environment variable or a repository recreates the problem that projected tokens removed: a secret you can no longer revoke. The old Secrets of type kubernetes.io/service-account-token, which never expired, are to be avoided for the same reason, except for a legacy tool that has no other way.

❌ Avoid: legacy static token
apiVersion: v1
kind: Secret
metadata:
name: lecteur-token
annotations:
kubernetes.io/service-account.name: lecteur
type: kubernetes.io/service-account-token

The signing of tokens can also be entrusted to an external service rather than to a key stored on the control plane. This setting is the cluster administrator's business and is covered in the Security module.

Demonstration: list Pods from a Pod

This demonstration gives an application the right to read the Pods of its namespace, then proves it from inside the Pod. It reuses the Role and the RoleBinding of the RBAC lesson. The namespace is called equipe, and the ServiceAccount lecteur.

Step 1: create the identity and bind the Role to it

The commands below create the namespace and the ServiceAccount, then a Role that grants get, list and watch on Pods, and finally the RoleBinding that binds it to lecteur. The syntax is explained in the lesson Kubernetes RBAC.

Terminal window
kubectl create namespace equipe
kubectl create serviceaccount lecteur -n equipe
kubectl create role lire-pods --verb=get,list,watch --resource=pods -n equipe
kubectl create rolebinding lecteur-lire-pods --role=lire-pods --serviceaccount=equipe:lecteur -n equipe
Output
namespace/equipe created
serviceaccount/lecteur created
role.rbac.authorization.k8s.io/lire-pods created
rolebinding.rbac.authorization.k8s.io/lecteur-lire-pods created

Step 2: start a Pod under this ServiceAccount

The client-api Pod uses the curl image, which serves here as an HTTP client to talk to the API from inside the Pod.

client-api.yaml
apiVersion: v1
kind: Pod
metadata:
name: client-api
namespace: equipe
spec:
serviceAccountName: lecteur
containers:
- name: curl
image: curlimages/curl:8.23.0@sha256:3fb7e13e5d179a845c97d78204f3f1064d1907037f26a3ebf91710571151fd93
command: ["sleep", "3600"]
Terminal window
kubectl apply -f client-api.yaml && kubectl wait --for=condition=Ready pod/client-api -n equipe --timeout=120s
Output
pod/client-api created
pod/client-api condition met

Step 3: call the API with the Pod's token

The API can be reached from the Pod at the address https://kubernetes.default.svc. The call presents the token in the Authorization header and verifies the server with the ca.crt certificate of the same directory. To keep the output readable, the grep filter only keeps the name of the Pod in the list received.

Terminal window
kubectl exec client-api -n equipe -- sh -c 'SA=/var/run/secrets/kubernetes.io/serviceaccount; curl -s --cacert $SA/ca.crt -H "Authorization: Bearer $(cat $SA/token)" https://kubernetes.default.svc/api/v1/namespaces/equipe/pods | grep "\"name\": \"client-api\"" | head -1'
Output
"name": "client-api",

The response is a list of Pods: the API recognized system:serviceaccount:equipe:lecteur and the Role gives it the right to list. The same identity, on a resource that the Role does not grant, receives a denial:

Terminal window
kubectl exec client-api -n equipe -- sh -c 'SA=/var/run/secrets/kubernetes.io/serviceaccount; curl -s -w "\nHTTP %{http_code}\n" --cacert $SA/ca.crt -H "Authorization: Bearer $(cat $SA/token)" https://kubernetes.default.svc/api/v1/namespaces/equipe/secrets'
Output
{
"kind": "Status",
"apiVersion": "v1",
"metadata": {},
"status": "Failure",
"message": "secrets is forbidden: User \"system:serviceaccount:equipe:lecteur\" cannot list resource \"secrets\" in API group \"\" in the namespace \"equipe\"",
"reason": "Forbidden",
"details": {
"kind": "secrets"
},
"code": 403
}
HTTP 403

Look at the message: it gives the subject (system:serviceaccount:equipe:lecteur), the verb (list), the resource (secrets) and the namespace. The exit code of the command is 0, because curl does not treat a 403 as an error without the -f option. The reliable check is the HTTP code, here 403.

Should the token be mounted in every Pod?

No. By default, Kubernetes mounts the token in every Pod, whether it needs it or not. If an attacker gets code execution in a container that never calls the API, they still find a valid identity there. Removing the mount costs nothing and reduces this risk. The table gives a few cases.

Type of workloadToken needed?
Static frontend (nginx, Caddy)No
Compute task or batch job that makes no API callNo
Application that reads ConfigMaps or Pods through the APIYes
Operator or controllerYes
Sidecar that contacts the APIYes

Cut the mount at Pod level

The automountServiceAccountToken: false field removes the volume and the mount for this Pod only. The sans-jeton Pod below uses the same lecteur ServiceAccount as client-api, which therefore keeps its RBAC rights: only the token is no longer mounted.

sans-jeton.yaml
apiVersion: v1
kind: Pod
metadata:
name: sans-jeton
namespace: equipe
spec:
serviceAccountName: lecteur
automountServiceAccountToken: false
containers:
- name: curl
image: curlimages/curl:8.23.0@sha256:3fb7e13e5d179a845c97d78204f3f1064d1907037f26a3ebf91710571151fd93
command: ["sleep", "3600"]
Terminal window
kubectl apply -f sans-jeton.yaml && kubectl wait --for=condition=Ready pod/sans-jeton -n equipe --timeout=120s
Output
pod/sans-jeton created
pod/sans-jeton condition met

The check to make is to see that the token is absent, in two places: in the Pod specification, then in the container.

Terminal window
kubectl get pod sans-jeton -n equipe -o jsonpath='automount={.spec.automountServiceAccountToken} volumes={.spec.volumes} mounts={.spec.containers[0].volumeMounts}{"\n"}'
Output
automount=false volumes= mounts=

The specification no longer contains any volume or any mount. In the container, the directory has disappeared:

Terminal window
kubectl exec sans-jeton -n equipe -- ls /var/run/secrets/kubernetes.io/serviceaccount/
Output
ls: /var/run/secrets/kubernetes.io/serviceaccount/: No such file or directory
command terminated with exit code 1

The No such file or directory message and the exit code 1 confirm that nothing is mounted. An application in this Pod that tried to call the API would have no token to present. In the measurement made, a call without a token arrives as system:anonymous and receives a 403.

Cut the mount for a whole ServiceAccount

To apply this behavior to all the Pods that use a ServiceAccount, the field is set on the ServiceAccount itself.

sa-sans-automount.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: frontend-sa
namespace: equipe
automountServiceAccountToken: false

When the Pod and the ServiceAccount both declare the field, the value of the Pod wins. The safest combination is therefore to cut the mount on the ServiceAccount, then to re-enable it explicitly with automountServiceAccountToken: true on the few Pods that call the API.

This setting does not affect Pods that are already running: the token is mounted when the Pod is created. To recreate the Pods of an existing Deployment with the new setting, run kubectl rollout restart deployment/<name> -n <namespace>. Projected tokens and their use to authenticate a workload are detailed in Machine identity and workload identity.

How do you tell whether a denial comes from RBAC or admission?

A Pod can be refused even though RBAC allows the caller. A request indeed goes through three stages in the API server: authentication identifies the caller, authorization (RBAC) checks its rights, then admission control checks that the resource itself is acceptable. The diagram shows this order: a denial at the second stage is an RBAC denial, a denial at the third is an admission denial.

How the API server processes a request in three successive stages: authentication identifies the caller (ServiceAccount token, certificate or OIDC), authorization checks the Role or ClusterRole through RBAC, then admission control checks that the resource is compliant (webhooks, PSA, quotas).How the API server handles a request① Authentication: who are you?ServiceAccount token, certificate, OIDC…② Authorization: are you allowed (RBAC)?Role or ClusterRole checked③ Admission control: is the resource compliant?webhooks validating/mutating, PSA, quotas…
Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %

Many denials start with Error from server (Forbidden), but not all. A ValidatingAdmissionPolicy that refuses a Pod created directly answers The pods "test" is invalid: : ValidatingAdmissionPolicy … denied request, without this prefix. For a Deployment, the same denial concerns its Pods: it appears as is forbidden: in the FailedCreate event of the ReplicaSet. The beginning of the message is therefore not enough: it is the rest of the message that designates the stage. The table gives the common cases.

SituationRBACAdmissionFragment to look for in the message
No Role allows creating Podsdeniednot reachedcannot create resource "pods"
Privileged Pod in a restricted namespaceaccepteddenied by Pod Security Admissionviolates PodSecurity
ResourceQuota exceededaccepteddenied by the quotaexceeded quota
Policy built into Kubernetes that refuses the resourceaccepteddenied by the ValidatingAdmissionPolicyValidatingAdmissionPolicy '…' with binding '…' denied request
Policy of an external tool that refuses the resourceaccepteddenied by the webhookadmission webhook "…" denied the request

The prefix of a webhook denial depends on the HTTP code that the webhook returns: it is not always (Forbidden), hence the value of looking for the fragment. The ValidatingAdmissionPolicy is taught in Manage container images in Kubernetes, where a policy refuses images without a digest.

If the Pod is created by a Deployment or a Job, the Pod never exists and the message does not appear at the kubectl apply command. For a Deployment, the FailedCreate event is carried by the ReplicaSet, not by the Deployment, whose kubectl describe only shows the ReplicaFailure True FailedCreate condition. To read the message of a Deployment, describe the ReplicaSet with kubectl describe replicaset -l <selector> -n <namespace>. For a Job, the event is carried by the Job itself: read it with kubectl describe job <name> -n <namespace>. In both cases, kubectl get events --field-selector reason=FailedCreate -n <namespace> finds the event.

Admission controllers are configured by the platform team, not by the developer. When a denial is not an RBAC denial, three reflexes help: look at the Pod Security labels of the namespace with kubectl get ns <namespace> --show-labels, look at the quotas with kubectl describe quota -n <namespace>, and ask for the list of active policies. The Pod Security level of a namespace is detailed in the lesson Pod Security Standards, and quotas in ResourceQuota and LimitRange. How admission controllers work is described in Admission controllers (in French).

Which habits should you keep day to day?

Three habits sum up the lesson. Give each application its ServiceAccount, with a readable name, and annotate it with its purpose so you know later whether it is still used. Cut the token mount as soon as the Pod does not call the API. Finally, check the rights from the Pod, with its own token, rather than only rereading the RBAC objects: what the API accepts is the only fact that counts, and kubectl auth can-i, explained in the RBAC lesson, checks it from your workstation.

Put it into practice

The identity of an application is checked with its own token, from its Pod. This lab starts from an application that refuses to start for lack of a ServiceAccount, has you create the identity, grant it through a Role the reading of the Pods of its namespace and nothing else, then prove from the inside that listing passes and that deleting, reading Secrets or looking elsewhere are denied. It also checks that a Pod that does not call the API has no token mounted.

The challenge of the module gives no step-by-step. It is graded on six states of equal weight, with a threshold of 70, two of which are blocking: reading the log of production and being unable to do anything more. It builds on this lesson, on the lesson Kubernetes RBAC, which explains the pods/log subresource and kubectl auth can-i --list, and on the lesson Security Context.

The collecte Pod must run under its own identity, hardened: non-root with a numeric UID, allowPrivilegeEscalation: false, read-only root and capabilities.drop: [ALL], while still doing its work. With its token, from its Pod, it must read the log of the commandes Pod in the production namespace. That is all: the collecte identity has no other right, anywhere. It can neither create, modify or delete anything in production, nor read its Secrets, nor look at another namespace, logs included, nor act on the cluster.

Two checks complete the grid. The running tableau Pod must carry no token. The default account of observatoire must keep no right, neither in its namespace nor elsewhere, beyond what Kubernetes gives to every account, such as asking about its own rights. The grade reads the effective policy computed by the API for each identity, not just a few denials.

Key takeaways

ConceptWhat to know
ServiceAccountIdentity of a workload, local to a namespace, with no right on the application when created (only the common basic rights)
default accountReceived by a Pod that declares nothing, shared by all the Pods of the namespace
serviceAccountNameSet in the Pod specification, and cannot be modified on an existing Pod
Projected tokenMounted in /var/run/secrets/kubernetes.io/serviceaccount/, bound to the Pod, renewed by the kubelet
Measured lifetimeThe volume asks for 3607 s, the token expires after one year through extension, warnafter marks the hour
kubectl create tokenOne-hour token by default, for a test, not to be stored
automountServiceAccountToken: falseRemoves the mount, the directory disappears from the container; the value of the Pod wins
Denialcannot … resource for RBAC, violates PodSecurity, exceeded quota, ValidatingAdmissionPolicy or admission webhook for admission

The golden rule fits in one sentence: the ServiceAccount is an identity, the permissions come from RBAC, and the token is only mounted if the application calls the API.

Test your knowledge

This quiz goes over the key distinctions of the lesson: identity versus permissions, token mounted or cut, real lifetime of a token, RBAC denial versus admission denial.

Knowledge check

Check what you have learned with this interactive quiz

7 questions
5 min
80% to pass

How it works

  • The timer starts when you click Start
  • Multiple choice, true/false and short answer questions
  • You can move between questions
  • Detailed results are shown at the end

Starts the quiz and the timer