← All articles

Kubernetes Service Account Token Rotation: A Walkthrough

Key takeaways

  • Projected service account tokens are refreshed by the kubelet at roughly 80% of their lifetime, so pods never hold a static credential.
  • The TokenRequest API issues short-lived, audience-bound tokens with a default expirationSeconds of one hour and a server-enforced minimum of 10 minutes.
  • Legacy token secrets can be found with kubectl by their secret type and the kubernetes.io/legacy-token-last-used annotation, then deleted after a 30 to 90 day observation window.
  • The LegacyServiceAccountTokenNoAutoGeneration gate (beta, default-on in Kubernetes 1.27+) stops automatic creation of long-lived secret-based tokens.
  • CI/CD runners should exchange identity for short-lived cloud credentials via IRSA or OIDC federation rather than exporting Kubernetes tokens outside the cluster.

Kubernetes service account token rotation today means bound, projected tokens: the kubelet requests short-lived credentials from the TokenRequest API and refreshes them before expiry, so pods never hold a static secret. This walkthrough covers the TokenRequest API, expiration and audience configuration, legacy token detection and cleanup, and rotation policies per workload type.

What is a Kubernetes service account token and how is it projected?

A service account token is the credential pods use to authenticate to the Kubernetes API. Every workload that talks to the API server does so as a service account, and the token it presents determines what that pod can do. Managing these tokens is the same lifecycle problem you have with AWS access keys and Stripe API keys: something expires, someone has to rotate it, and nobody remembers who owns it.

Legacy token secrets vs projected tokens

Legacy service account tokens were long-lived secrets stored in Kubernetes Secrets, mounted automatically into every pod, and valid forever unless you deleted them manually. Projected tokens, introduced with the TokenRequest API, are short-lived, bound to a pod and an audience, and expire on their own. When the pod dies, the token's validity ends with it.

How kubelet projection and refresh work

With a kubernetes.io projected volume, the kubelet requests a token from the TokenRequest API and writes it into the pod's filesystem. The kubelet refreshes the token when it nears expiry, typically once it has less than two-thirds of its total lifetime remaining, so a long-running pod always has a fresh credential without human involvement. Rotation happens in place: the file updates, the pod re-reads it, and the old token expires on schedule. That removes humans from the transport layer for in-cluster credentials, though you still need a way to track expiry deadlines for everything outside the cluster, as covered in alternatives to manual credential rotation tracking.

How does the TokenRequest API rotate service account tokens?

Anatomy of a TokenRequest call

A pod or controller asks the API server for a token by POSTing a TokenRequest against a service account: kubectl create token my-sa --audience=api://my-api --duration=3600s or the equivalent API call. The request carries three fields that matter: spec.audiences (who can accept the token), spec.expirationSeconds (the lifetime cap), and an optional bound object reference tying the token to a pod. The API server returns a time-limited token plus its expiry timestamp. Because the token is issued, not stored, there is nothing in etcd to leak or clean up later.

Renewal timing and the 80% lifetime heuristic

Clients that use projected tokens do not track expiry themselves; the kubelet handles it. The kubelet refreshes a projected service account token when the token has consumed roughly 80% of its lifetime, or if the token is older than the minimum refresh window, whichever comes first. With the default one-hour lifetime, that means a fresh token is requested around the 48-minute mark, and the volume file is swapped in place. Pods read the same path, so renewal is invisible to the workload. If your pods run long and you set expirationSeconds to 24 hours, the kubelet still reissues well before expiry, so a missed refresh never surfaces as an auth failure mid-flight.

What rotates automatically vs what you must handle

The kubelet's 80% refresh covers only tokens projected into pods via the projected volume type. Three gaps remain: tokens you mint with kubectl create token or direct TokenRequest calls for CI jobs and external consumers, which expire and never renew; bound tokens outliving their pod, which vanish when the pod dies but still need re-issuance logic in controllers; and non-Kubernetes credentials, like AWS keys or Stripe API keys, which follow your own 30/60/90 day rotation policy with no kubelet to help. KeyGuardRail tracks the deadlines for the second and third categories as metadata only, so you know which token or key is nearing expiry and who owns it, without ever holding the secret value. For a walkthrough of automating the rotation side, see our brief on automation access (https://keyguardrail.com/brief/automation-access-september-2026).

How do you configure token expiration and audience bindings?

expirationSeconds defaults and limits

When you call the TokenRequest API, the default expirationSeconds is one hour, and the API server clamps requests to a minimum of 10 minutes and a maximum defined by --service-account-max-token-expiration on the kube-apiserver. Set the field explicitly in your TokenRequest spec rather than relying on the default, so a rotation policy of 30/60/90 day thinking gets replaced by short-lived creds wherever the workload allows. See the Kubernetes API reference for TokenRequest for the exact field bounds.

Audience binding with apiServer audiences

The audiences field restricts where a token can be presented. A token bound to a single audience cannot be replayed against a different API consumer, which shrinks the blast radius of a leaked token to one service.

Pod spec examples

With projected volumes, set expirationSeconds: 3600 and audience: vault (illustrative) in the serviceAccountToken block; kubelet refreshes the token at roughly 80% of its lifetime. If you track expiry metadata for these tokens alongside Stripe and GitHub keys, KeyGuardRail handles that without holding the secret value itself, per our terms.

How do you detect and migrate legacy long-lived service account tokens?

Finding legacy token secrets with kubectl

Auto-generated tokens live as Kubernetes secrets of type kubernetes.io/service-account-token. List them with kubectl get secrets --all-namespaces --field-selector type=kubernetes.io/service-account-token. Manually created tokens won't always match that pattern, so also grep controller manifests and CI configs for pods mounting token secrets by name. Any secret carrying the kubernetes.io/legacy-token-last-used annotation is confirmed legacy; ones without it may be unused and safe to delete after a grace period.

Migration steps for workloads and controllers

Projected tokens need no volume changes in most cases: Kubernetes mounts one at /var/run/secrets/kubernetes.io/serviceaccount/token automatically when the pod uses the default service account token. For custom audiences or shorter lifetimes, add a projected volume with serviceAccountToken and set expirationSeconds to match your 30/60/90 day rotation policy, or shorter for short-lived creds. Restart deployments one namespace at a time and confirm the mounted token's exp claim changes on pod restart.

Cleaning up orphaned token secrets

After cutover, delete the legacy secrets backing migrated workloads. Track which secrets map to which owner before you delete; an expiry-tracking layer like KeyGuardRail gives you that metadata-only inventory, and our guide to credential expiration reminder tools for IT teams covers the reminder workflow (https://keyguardrail.com/blog/credential-expiration-reminder-tools-for-it-teams).

How does the LegacyServiceAccountTokenNoAutoGeneration feature gate affect rotation?

Gate behavior and version defaults

LegacyServiceAccountTokenNoAutoGeneration stops the TokenRequest controller from auto-generating long-lived secret-based tokens for every service account. When enabled, no secret token exists until something explicitly requests one through the TokenRequest API, so projected, short-lived tokens become the default issuance path instead of the fallback. The gate is beta and enabled by default in Kubernetes 1.27+, per the Kubernetes documentation on LegacyServiceAccountTokenNoAutoGeneration.

Extended expiration and LegacyServiceAccountTokenCleanUp

The companion gate LegacyServiceAccountTokenCleanUp handles the backlog: it deletes legacy secret-based tokens unused for the configured duration (one year by default). Together they close the gap where pods keep mounting tokens nobody tracks.

Practically, enabling both means every remaining long-lived token is one somebody deliberately created, which makes ownership and expiry tracking a bounded problem rather than a sprawl audit. Inventory what survives before you rely on the cleanup window; a token renewed by any use resets the clock. We track these deadlines alongside your other expiring credentials in our October 2026 credentials brief.

How do you audit service account token usage across a cluster?

Before you revoke or rotate anything, you need evidence of which service accounts and tokens are actually in use. Three sources cover it: audit logs, TokenReview responses, and Kubernetes metrics.

Audit log fields for token authentication

Enable API server audit logging and filter on authentication.k8s.io. For projected tokens, each authenticated request carries the service account's namespace, name, and UID, plus the pod UID and volume name in the user.extra field. That pod UID is your link between a token and the specific workload using it. Legacy tokens authenticate without pod metadata, which is itself a useful detection signal.

Last-used signals and metrics

The authentication.k8s.io/v1 TokenRequest API does not track last use, but the API server exposes serviceaccount_sts_tokens_total and serviceaccount_legacy_tokens_total metrics. Any legacy token request after 1.22 means something outside a pod is still authenticating with a mounted secret. Record these metrics over a full rotation cycle, typically 30 to 90 days, before declaring a credential dead.

Building a usage inventory

Correlate audit log entries by service account UID into a simple inventory: last seen timestamp, source pod or IP, and whether authentication used a bound or legacy token. Anything with no hits across your observation window is a candidate for revocation. This is the same metadata-only approach you want for API keys and SaaS credentials: track ownership, last use, and expiry without ever touching the secret value itself.

How should rotation policies differ for pods, controllers, and CI/CD workloads?

One rotation policy across every workload type is the wrong default. In-cluster pods, long-running controllers, and external CI runners have different trust boundaries, so they need different renewal mechanics.

In-cluster pods: rely on projection

Pods using projected service account tokens get kubelet-driven renewal automatically, with tokens refreshed near expiry and no code changes required. Your rotation policy here is a monitoring policy: confirm workloads actually mount projected tokens instead of legacy secrets.

Controllers and operators: renewal loops

Operators and CRD controllers run for months, so their tokens outlive any 30/60/90 day rotation window. Build a renewal loop that calls the TokenRequest API before expiry, or set a tighter bound on --service-account-extend-token-expiration if you rely on extended legacy tokens, per the Kubernetes documentation on legacy token cleanup and extended expiration.

CI/CD and external consumers: avoid exporting tokens

WorkloadRotation mechanismPolicy
In-cluster podKubelet projectionAudit mounts
Controller/operatorTokenRequest renewal loopRenew before expiry
CI/CD runnerShort-lived cloud creds (IRSA, OIDC federation)Never export tokens

External runners should exchange identity for short-lived cloud credentials rather than carrying a Kubernetes token out of the cluster.

How do you track token and credential expiry deadlines alongside your other secrets?

Projected service account tokens expire on a schedule you set, but they are one credential among dozens. A Stripe key, a GitHub PAT, and an IAM user access key all carry their own expiry and rotation deadlines, and most vaults store the secret value without tracking who owns it or when it is due. That is the gap: the vault holds secrets, not lifecycle metadata.

Metadata-only lifecycle tracking

KeyGuardRail monitors credential lifecycle metadata, not secret values. You register an AWS Secrets Manager entry, a Stripe API key, or a Kubernetes service account token deadline, and it tracks expiry dates and rotation history without ever taking custody of the secret itself. Your vault stays the source of truth for values.

Assigning owners and rotation deadlines

Each credential gets an owner ("Payments platform", "Platform engineering") and a rotation deadline, so a 30/60/90 day rotation policy becomes a tracked obligation instead of a wiki page. When a token or key approaches expiry, the right owner knows. Self-serve signup on the Starter plan gets you the first inventory in an afternoon.

FAQ

Do projected service account tokens rotate automatically, or do I need a CronJob?

The kubelet handles it for you. It requests a fresh token from the TokenRequest API once the current one has consumed roughly 80% of its lifetime, then swaps the file in place at the same path. No CronJob and no code changes are needed. CronJob-style renewal loops are only needed for controllers minting their own tokens or CI jobs outside pod projection.

What is the maximum expirationSeconds I can set on a TokenRequest?

The cap is whatever your API server operator set via --service-account-max-token-expiration on the kube-apiserver; there is no universal number. The server also enforces a minimum of 10 minutes. If you omit expirationSeconds, the default is one hour. Check the flag value on your cluster before assuming a longer lifetime will be honored.

Is it safe to mount a service account token in a CI/CD runner outside the cluster?

No. Exporting a Kubernetes token outside the cluster defeats the pod binding and audience restrictions that limit a leaked token's blast radius. Exchange the runner's identity for short-lived cloud credentials instead, using IRSA or OIDC federation. The runner never holds a Kubernetes credential, and expiry is handled by the cloud provider rather than your pipeline.

How can I tell if a legacy service account token secret is still being used before deleting it?

Check for the kubernetes.io/legacy-token-last-used annotation, which confirms recent use. Then watch the serviceaccount_legacy_tokens_total metric and audit logs over a full observation window, typically 30 to 90 days. A token with no hits across that window is a deletion candidate; one that gets used resets the cleanup clock.

Does rotating a service account token break running pods?

Not for projected tokens. The kubelet refreshes them in place, the file path stays the same, and the old token expires on its own schedule, so a long-running pod always holds a valid credential. Breaking changes come from deleting legacy token secrets that pods still mount, so inventory ownership and usage before removing anything.