Give a Pod an identity with a ServiceAccount: projected token, real lifetime, calling the API from the Pod, cutting the token, RBAC versus admission denials.
The issue opens pre-filled with this page title and URL.
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.
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:
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/.
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.
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
kubectlcreatetokenlecteur-nequipe
kubectlcreatetokenlecteur-nequipe--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.
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.
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:
"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 workload
Token needed?
Static frontend (nginx, Caddy)
No
Compute task or batch job that makes no API call
No
Application that reads ConfigMaps or Pods through the API
Yes
Operator or controller
Yes
Sidecar that contacts the API
Yes
Swipe to see more
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.
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.
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.
Situation
RBAC
Admission
Fragment to look for in the message
No Role allows creating Pods
denied
not reached
cannot create resource "pods"
Privileged Pod in a restricted namespace
accepted
denied by Pod Security Admission
violates PodSecurity
ResourceQuota exceeded
accepted
denied by the quota
exceeded quota
Policy built into Kubernetes that refuses the resource
accepted
denied by the ValidatingAdmissionPolicy
ValidatingAdmissionPolicy '…' with binding '…' denied request
Policy of an external tool that refuses the resource
accepted
denied by the webhook
admission webhook "…" denied the request
Swipe to see more
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
Concept
What to know
ServiceAccount
Identity of a workload, local to a namespace, with no right on the application when created (only the common basic rights)
default account
Received by a Pod that declares nothing, shared by all the Pods of the namespace
serviceAccountName
Set in the Pod specification, and cannot be modified on an existing Pod
Projected token
Mounted in /var/run/secrets/kubernetes.io/serviceaccount/, bound to the Pod, renewed by the kubelet
Measured lifetime
The volume asks for 3607 s, the token expires after one year through extension, warnafter marks the hour
kubectl create token
One-hour token by default, for a test, not to be stored
automountServiceAccountToken: false
Removes the mount, the directory disappears from the container; the value of the Pod wins
Denial
cannot … resource for RBAC, violates PodSecurity, exceeded quota, ValidatingAdmissionPolicy or admission webhook for admission
Swipe to see more
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
⏱️--:--
0 / 7
Review
(0/0)
--:--
0%
0Correct
0To review
0:00Time
-Level
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.