kubernetes

Kubernetes ServiceAccount

Kubernetes ServiceAccount Explained

By Shubhankar Tripathi • • 5 min read

Kubernetes ServiceAccount Explained

bitcodematrix.com | Kubernetes Series

1. Introduction

When you run kubectl, the API server knows who you are from your credentials. But what about the programs that run inside the cluster: a controller that watches Pods, a CI runner that deploys applications, a monitoring agent that lists endpoints, or an application that must read a ConfigMap at start-up? They need an identity too, and in Kubernetes that identity is the ServiceAccount.

This article explains ServiceAccounts from the ground up. You will learn how they differ from human users, how a Pod receives its identity and token, how modern bound tokens work and how they replace the old long-lived ones, how to authorize a ServiceAccount with RBAC, how it connects to cloud identity systems, and how to secure and troubleshoot it. It complements the earlier articles in this series on Secrets and on the control plane.

2. Identity in Kubernetes: Users and ServiceAccounts

Kubernetes distinguishes two kinds of identities that call its API:

Aspect

Normal users

ServiceAccounts

Who they are

People and external systems

Processes running in Pods inside the cluster

Represented in the API

No. Kubernetes has no User object

Yes. ServiceAccount is a namespaced API object

Managed by

An external identity provider, certificates or tokens issued outside Kubernetes

Kubernetes itself

Scope

Cluster-wide

Belongs to one namespace

Credential

Client certificate, OIDC token or similar

A signed token, normally delivered to the Pod automatically

Name seen by RBAC

Whatever the identity provider asserts

system:serviceaccount:<namespace>:<name>

 

Every authenticated ServiceAccount also belongs to two groups, system:serviceaccounts for all of them and system:serviceaccounts:<namespace> for those in one namespace. RBAC rules can refer to these groups, although binding to specific ServiceAccounts is almost always safer.

3. What Is a ServiceAccount?

A ServiceAccount is a small object that exists mainly to be a name that other objects can refer to: Pods run as it, and RBAC bindings grant permissions to it.

apiVersion: v1

kind: ServiceAccount

metadata:

  name: app-sa

  namespace: shop

automountServiceAccountToken: true

imagePullSecrets:

- name: regcred

Field

Meaning

metadata.name and namespace

The identity. The full RBAC name becomes system:serviceaccount:shop:app-sa

automountServiceAccountToken

Whether Pods that use this account get an API token mounted automatically. A Pod can override it

imagePullSecrets

Registry credentials that are added to every Pod that runs as this ServiceAccount

secrets (legacy)

References to token Secrets in older clusters; not used by current versions for automatic tokens

 

3.1 The default ServiceAccount

Every namespace automatically gets a ServiceAccount called default. Any Pod that does not name a ServiceAccount runs as it. The default account has no special permissions beyond the basic access that all authenticated identities receive, such as API discovery, so it is harmless until someone grants it more. That is exactly the danger: if a team binds a powerful role to default for convenience, every Pod in the namespace that does not specify an account inherits that power.

3.2 Naming and Lifecycle

  • ServiceAccounts are namespaced, and a Pod can use only a ServiceAccount from its own namespace.

  • Creating one is cheap, so create one per workload or per role, not one for the whole namespace.

  • Deleting a namespace deletes its ServiceAccounts, and deleting a ServiceAccount invalidates the tokens that were issued for it.

  • You cannot change a running Pod's ServiceAccount. Change the Pod template and let the controller replace the Pods.

4. How a Pod Gets Its Identity

The mechanism is largely automatic, and understanding its steps explains most of the behaviour you will see:

  1. You create a Pod, optionally with spec.serviceAccountName. If you omit it, the ServiceAccount admission controller sets it to default. If the named account does not exist, the Pod is rejected.

  2. Unless token mounting is disabled, the admission controller adds a projected volume to the Pod, which combines a service account token, the cluster CA certificate and the namespace name.

  3. When the Pod starts on a node, the kubelet asks the API server for a token for that ServiceAccount through the TokenRequest API. The token is bound to this particular Pod and has an expiry time.

  4. The kubelet writes the token into the projected volume and refreshes it before it expires, so the file always contains a valid token while the Pod runs.

  5. The application reads the token from the file and sends it as a bearer token in requests to the API server. The API server validates the signature, the expiry, the audience and the binding to the Pod, and then authorizes the request with RBAC.

Inside the container, the volume appears at a well-known path:

Path

Content

/var/run/secrets/kubernetes.io/serviceaccount/token

The signed token (a JWT)

/var/run/secrets/kubernetes.io/serviceaccount/ca.crt

The cluster CA certificate, for verifying the API server

/var/run/secrets/kubernetes.io/serviceaccount/namespace

The namespace of the Pod

 

Official client libraries know this convention. Their in-cluster configuration functions, for example in the Go and Python clients, locate the API server through environment variables and read these files automatically, and they re-read the token when it rotates. Applications that cache a token for a long time may start to fail with authentication errors after it expires, so rely on the library rather than reading the file once.

5. Tokens in Depth

5.1 Bound Tokens

Modern clusters issue bound service account tokens, which are a major security improvement over the original design. They have these properties:

Property

What it means

Time-limited

Each token has an expiry, around one hour by default for tokens in the automatic volume, and the kubelet renews it

Audience-bound

The token states which service it is meant for. By default, that is the Kubernetes API server. Other services can require their own audience

Object-bound

The token is tied to the Pod (and its ServiceAccount). When the Pod is deleted, the token stops being valid

Automatically rotated

The kubelet refreshes the file, so no manual rotation is needed

Signed

The API server signs it with a key, and it can be verified by anyone who has the matching public key

 

5.2 What Is Inside the Token

The token is a JSON Web Token (JWT). You can look at its claims by decoding the middle part. The base64 data may need padding to decode cleanly, but the content is readable:

TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)

echo "$TOKEN" | cut -d. -f2 | base64 -d 2>/dev/null

The decoded claims include the issuer (iss), the subject (sub, such as system:serviceaccount:shop:app-sa), the audience (aud), the issue and expiry times, and a Kubernetes-specific section that names the namespace, the ServiceAccount and the Pod that the token is bound to. Decoding is for understanding only: the token is a credential, so do not paste real tokens into tickets, chats or public tools.

5.3 Requesting a Token Yourself

The TokenRequest API issues tokens on demand. With kubectl:

kubectl create token app-sa -n shop

kubectl create token app-sa -n shop --duration=30m

kubectl create token app-sa -n shop --audience=https://api.example.com

This is the right way to get a credential for a ServiceAccount, for example for a pipeline, for short tasks or for testing. The token is short-lived and is not stored anywhere in the cluster.

5.4 Legacy Long-Lived Tokens

In older clusters, Kubernetes automatically created a Secret for every ServiceAccount, holding a token that never expired and was not bound to any Pod. These tokens were a serious risk: if one leaked, it worked until someone deleted it. Since Kubernetes 1.24, such Secrets are no longer created automatically. If an external system truly cannot use short-lived tokens, you can still create one by hand, as a Secret of type kubernetes.io/service-account-token with an annotation naming the account:

apiVersion: v1

kind: Secret

metadata:

  name: app-sa-token

  namespace: shop

  annotations:

    kubernetes.io/service-account.name: app-sa

type: kubernetes.io/service-account-token

The control plane then fills in the token. Treat this as a last resort and protect it like any high-value secret.

5.5 Finding and Retiring Old Tokens

Clusters that were upgraded from older versions may still hold legacy token Secrets, and some of them may still be in use. Find them and replace their consumers:

kubectl get secrets -A --field-selector type=kubernetes.io/service-account-token

Recent Kubernetes versions track when a legacy token was last used, through an annotation or label on the Secret and through metrics, which helps you to identify which ones are safe to delete. Check the documentation of your version for the details, then move the consumers to TokenRequest or projected tokens and delete the old Secrets.

6. Authorizing a ServiceAccount with RBAC

Authentication only proves who the caller is. What it may do is decided by authorization, usually RBAC. A new ServiceAccount can do almost nothing. You grant permissions with a Role (a set of allowed actions in a namespace) and a RoleBinding that attaches the Role to the ServiceAccount:

apiVersion: rbac.authorization.k8s.io/v1

kind: Role

metadata:

  name: pod-reader

  namespace: shop

rules:

- apiGroups: [""]

  resources: ["pods"]

  verbs: ["get", "list", "watch"]

---

apiVersion: rbac.authorization.k8s.io/v1

kind: RoleBinding

metadata:

  name: app-sa-pod-reader

  namespace: shop

subjects:

- kind: ServiceAccount

  name: app-sa

  namespace: shop

roleRef:

  kind: Role

  name: pod-reader

  apiGroup: rbac.authorization.k8s.io

The subjects entry names the ServiceAccount and its namespace, which matters because the binding could live in a different namespace than the account. Check the result with kubectl auth can-i, impersonating the account:

kubectl auth can-i list pods -n shop \

  --as=system:serviceaccount:shop:app-sa

kubectl auth can-i delete pods -n shop \

  --as=system:serviceaccount:shop:app-sa

kubectl auth can-i --list -n shop \

  --as=system:serviceaccount:shop:app-sa

6.1 Namespace and Cluster Scope

Binding

Effect for a ServiceAccount

Role plus RoleBinding in a namespace

Permissions apply only in that namespace. The usual choice

ClusterRole plus RoleBinding

Reuses a common set of rules, but limits them to the namespace of the binding

ClusterRole plus ClusterRoleBinding

Permissions across all namespaces and cluster-scoped resources. Use sparingly, for controllers that truly need it

 

Grant only the verbs and resources the workload needs, prefer resourceNames for single objects where possible, and avoid wildcards. Never bind cluster-admin to an application ServiceAccount, because a compromise of that Pod would then be a compromise of the cluster.

7. Using a ServiceAccount in a Workload

Set the account in the Pod template, and decide deliberately whether the Pod needs an API token at all:

apiVersion: apps/v1

kind: Deployment

metadata:

  name: web

  namespace: shop

spec:

  replicas: 2

  selector:

    matchLabels:

      app: web

  template:

    metadata:

      labels:

        app: web

    spec:

      serviceAccountName: app-sa

      automountServiceAccountToken: false

      containers:

      - name: web

        image: nginx:1.27

Most application Pods never call the Kubernetes API, and for them the best setting is automountServiceAccountToken: false. No token is mounted, so a compromised process has no credential to steal. Set it on the ServiceAccount to make it the default for everything that uses the account, and on the Pod to override the account setting. Enable mounting only for workloads that need the API, such as controllers, operators, CI agents and monitoring components.

7.1 Tokens for Other Audiences

If a workload must authenticate to a service other than the Kubernetes API, request a token with a specific audience through a projected volume. The token is again short-lived and refreshed by the kubelet:

spec:

  serviceAccountName: app-sa

  containers:

  - name: app

    image: example/app:1.0

    volumeMounts:

    - name: vault-token

      mountPath: /var/run/secrets/tokens

      readOnly: true

  volumes:

  - name: vault-token

    projected:

      sources:

      - serviceAccountToken:

          path: vault-token

          audience: vault

          expirationSeconds: 3600

The receiving service can verify the token with the cluster's public keys and check that the audience matches its own name, which prevents a token meant for one service from being replayed against another.

8. Image Pull Secrets Through a ServiceAccount

Adding imagePullSecrets to a ServiceAccount makes the credentials apply to every Pod that runs as it, so you do not have to repeat them in each manifest:

kubectl patch serviceaccount app-sa -n shop \

  -p '{"imagePullSecrets":[{"name":"regcred"}]}'

This is convenient for private registries, but remember that the Secret must exist in the same namespace, and that every Pod using the ServiceAccount, including ones created later, gets the registry credentials. Use a dedicated account for that purpose if you want to limit where they are available.

9. Workload Identity: From Kubernetes to External Systems

A particularly valuable use of ServiceAccounts is to give Pods access to cloud services and other external systems without static keys. The API server acts as an OpenID Connect (OIDC) identity provider: it signs tokens with a known issuer and publishes its public keys through a discovery endpoint. An external system is configured to trust that issuer and to map a ServiceAccount identity to a role in its own world.

The flow works like this:

  • The Pod gets a projected token with an audience that the external system expects.

  • The workload, or the cloud SDK inside it, presents that token to the external security token service.

  • The external service verifies the signature through the cluster's published keys, checks the issuer, audience and subject, and, if they match a configured trust rule, returns short-lived credentials for the mapped role.

  • The workload uses those temporary credentials to call the cloud API.

Major platforms provide this as a product: IAM roles for service accounts on Amazon EKS, Workload Identity on Google Kubernetes Engine and Azure Workload Identity on AKS. They usually work by annotating the ServiceAccount with the identity to assume, and some require a label on the Pod. The annotation names are specific to each provider, so follow the provider's documentation. A generic outline looks like this:

apiVersion: v1

kind: ServiceAccount

metadata:

  name: uploader

  namespace: shop

  annotations:

    # provider-specific; the key and value format depend on the platform

    example.com/cloud-role: <role-identifier>

The benefits are significant: no long-lived cloud keys in Secrets, automatic rotation, an audit trail that names the Kubernetes identity, and precise permissions per workload. Use one ServiceAccount per distinct cloud role, since the trust rule is attached to that identity.

10. Security Considerations

Risk

Mitigation

Every Pod receives an API token by default, even when it does not need one

Set automountServiceAccountToken to false on accounts and Pods that do not call the API

The default ServiceAccount accumulates permissions

Never bind roles to default, and use a dedicated ServiceAccount for every workload that needs access

Over-broad roles, wildcards or cluster-admin

Grant least privilege, review bindings regularly and audit what each ServiceAccount can do with kubectl auth can-i --list

Anyone who can create Pods in a namespace can run them as any ServiceAccount there

Restrict who can create Pods, and keep powerful ServiceAccounts in namespaces with tight access and admission policies

A leaked token

Bound tokens expire and die with the Pod. Avoid legacy token Secrets. Rotate by recreating Pods, and delete the ServiceAccount if compromised

Token theft from a compromised container

Run as non-root, drop capabilities, use read-only root file systems, and restrict egress to the API server with NetworkPolicies where possible

Long-lived static cloud keys in Secrets

Replace them with workload identity federation

Unknown activity

Enable audit logging, and watch for unusual calls made by ServiceAccounts, especially reading Secrets or creating Pods

 

A good mental model: the token in a Pod is a credential that any process in that Pod can read. Whatever the ServiceAccount is allowed to do, an attacker who gains code execution in the container can do too. Design the permissions as if that will happen.

11. Hands-On Walkthrough

  1. Create a namespace, a ServiceAccount and a Role that can read Pods.

kubectl create namespace sa-demo

kubectl create serviceaccount reader -n sa-demo

kubectl create role pod-reader -n sa-demo \

  --verb=get,list,watch --resource=pods

kubectl create rolebinding reader-binding -n sa-demo \

  --role=pod-reader --serviceaccount=sa-demo:reader

  1. Check what the account can and cannot do.

kubectl auth can-i list pods -n sa-demo --as=system:serviceaccount:sa-demo:reader

kubectl auth can-i list secrets -n sa-demo --as=system:serviceaccount:sa-demo:reader

  1. Run a Pod that uses the account, and call the API from inside it with the mounted token.

apiVersion: v1

kind: Pod

metadata:

  name: api-caller

  namespace: sa-demo

spec:

  serviceAccountName: reader

  containers:

  - name: curl

    image: curlimages/curl:8.8.0

    command: ["sleep", "3600"]

kubectl exec -n sa-demo api-caller -- 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/sa-demo/pods'

The call succeeds and returns the Pod list. Change the URL to the Secrets endpoint and you get a 403 Forbidden response, because the Role does not allow it.

  1. Disable token mounting and see the difference.

kubectl patch serviceaccount reader -n sa-demo \

  -p '{"automountServiceAccountToken": false}'

kubectl delete pod api-caller -n sa-demo

After you recreate the Pod from the same manifest, the directory /var/run/secrets/kubernetes.io/serviceaccount no longer exists, and the API call has no credential to use.

  1. Clean up.

kubectl delete namespace sa-demo

12. Troubleshooting

Symptom

Likely cause and check

Pod not created: serviceaccount not found

The ServiceAccount named in the Pod does not exist in that namespace. Create it, or fix the name

403 Forbidden: cannot list resource "pods" in API group "" in the namespace

The ServiceAccount lacks the permission. Add a Role and RoleBinding, and check the subject name and namespace

403 for cluster-scoped resources

A namespaced Role cannot grant access to cluster-wide resources such as nodes. Use a ClusterRole with a ClusterRoleBinding if truly needed

Binding exists but has no effect

The subject namespace is wrong or missing, the roleRef points to the wrong object, or the binding is in another namespace. Verify with kubectl auth can-i using impersonation

401 Unauthorized after running for a while

The application cached an expired token. Use a client library that reloads the token file, or re-read it periodically

No token directory in the container

automountServiceAccountToken is false on the Pod or ServiceAccount. Enable it for workloads that need the API

Expected token Secret does not exist

Clusters since 1.24 do not create them automatically. Use TokenRequest or a projected token, or create a legacy Secret deliberately if required

External service rejects the token

Wrong audience, an untrusted issuer, an expired token or a mismatched subject. Decode the claims and compare them with the trust configuration

Cloud access denied from a Pod

The ServiceAccount annotation or Pod label for workload identity is missing, the trust rule names a different namespace or account, or the cloud role lacks permissions

Pod cannot reach the API server

A NetworkPolicy blocks egress to the API server, or the in-cluster service address is not reachable. Test connectivity from a debug Pod

Image pull fails although credentials exist

imagePullSecrets is on a different ServiceAccount than the Pod uses, or the Secret is in another namespace

 

When in doubt, ask Kubernetes: impersonate the account with kubectl auth can-i, read the exact error message from the API response, and compare the subject name in the denial with the subject in your binding.

13. Best Practices

  • Create a dedicated ServiceAccount for every workload, and never use default for anything that needs permissions.

  • Disable automatic token mounting for every Pod that does not call the Kubernetes API.

  • Grant least privilege with namespaced Roles, specific verbs and resources, and avoid wildcards and cluster-admin.

  • Prefer bound, short-lived tokens through the automatic volume, TokenRequest or projected volumes, and retire legacy token Secrets.

  • Use audience-specific projected tokens for external services, and let those services verify the issuer and audience.

  • Use workload identity federation for cloud access instead of long-lived keys stored in Secrets.

  • Control who can create Pods, and who can bind roles, because both are paths to higher privileges.

  • Review ServiceAccounts, bindings and their effective permissions regularly, and delete the unused ones.

  • Enable audit logging and alert on unusual use of ServiceAccount identities.

  • Harden the Pods themselves, with non-root users, restricted capabilities and network policies, so that token theft is hard.

  • Test permissions with kubectl auth can-i in CI before rollout, and keep RBAC manifests in version control with reviews.

14. Conclusion

A ServiceAccount is the answer to a simple question: who is this Pod, as far as the Kubernetes API and the outside world are concerned? Its tokens are now short-lived, audience-bound and tied to the Pod that holds them, which makes them far safer than the permanent tokens of older clusters. RBAC then turns that identity into precise permissions, and workload identity extends it to cloud services without any stored keys.

The risks come from convenience: sharing the default account, mounting tokens where they are not needed and granting broad roles. If you give each workload its own ServiceAccount, mount the token only when required, grant the minimum permissions and prefer federated, short-lived credentials, your workloads get exactly the access they need and no more.