Service Accounts

Learn about ServiceAccount objects in Kubernetes.

This page introduces the ServiceAccount object in Kubernetes, providinginformation about how service accounts work, use cases, limitations,alternatives, and links to resources for additional guidance.

What are service accounts?

A service account is a type of non-human account that, in Kubernetes, providesa distinct identity in a Kubernetes cluster. Application Pods, systemcomponents, and entities inside and outside the cluster can use a specificServiceAccount's credentials to identify as that ServiceAccount. This identityis useful in various situations, including authenticating to the API server orimplementing identity-based security policies.

Service accounts exist as ServiceAccount objects in the API server. Serviceaccounts have the following properties:

  • Namespaced: Each service account is bound to a Kubernetesnamespace. Every namespacegets adefault ServiceAccount upon creation.

  • Lightweight: Service accounts exist in the cluster and aredefined in the Kubernetes API. You can quickly create service accounts toenable specific tasks.

  • Portable: A configuration bundle for a complex containerized workloadmight include service account definitions for the system's components. Thelightweight nature of service accounts and the namespaced identities makethe configurations portable.

Service accounts are different from user accounts, which are authenticatedhuman users in the cluster. By default, user accounts don't exist in the KubernetesAPI server; instead, the API server treats user identities as opaquedata. You can authenticate as a user account using multiple methods. SomeKubernetes distributions might add custom extension APIs to represent useraccounts in the API server.

Comparison between service accounts and users
DescriptionServiceAccountUser or group
LocationKubernetes API (ServiceAccount object)External
Access controlKubernetes RBAC or otherauthorization mechanismsKubernetes RBAC or other identity and access management mechanisms
Intended useWorkloads, automationPeople

Default service accounts

When you create a cluster, Kubernetes automatically creates a ServiceAccountobject nameddefault for every namespace in your cluster. Thedefaultservice accounts in each namespace get no permissions by default other than thedefault API discovery permissionsthat Kubernetes grants to all authenticated principals if role-based access control (RBAC) is enabled.If you delete thedefault ServiceAccount object in a namespace, thecontrol planereplaces it with a new one.

If you deploy a Pod in a namespace, and you don'tmanually assign a ServiceAccount to the Pod, Kubernetesassigns thedefault ServiceAccount for that namespace to the Pod.

Use cases for Kubernetes service accounts

As a general guideline, you can use service accounts to provide identities inthe following scenarios:

  • Your Pods need to communicate with the Kubernetes API server, for example insituations such as the following:
    • Providing read-only access to sensitive information stored in Secrets.
    • Grantingcross-namespace access, such as allowing aPod in namespaceexample to read, list, and watch for Lease objects inthekube-node-lease namespace.
  • Your Pods need to communicate with an external service. For example, aworkload Pod requires an identity for a commercially available cloud API,and the commercial provider allows configuring a suitable trust relationship.
  • Authenticating to a private image registry using animagePullSecret.
  • An external service needs to communicate with the Kubernetes API server. Forexample, authenticating to the cluster as part of a CI/CD pipeline.
  • You use third-party security software in your cluster that relies on theServiceAccount identity of different Pods to group those Pods into differentcontexts.

How to use service accounts

To use a Kubernetes service account, you do the following:

  1. Create a ServiceAccount object using a Kubernetesclient likekubectl or a manifest that defines the object.

  2. Grant permissions to the ServiceAccount object using an authorizationmechanism such asRBAC.

  3. Assign the ServiceAccount object to Pods during Pod creation.

    If you're using the identity from an external service,retrieve the ServiceAccount token and use it from thatservice instead.

For instructions, refer toConfigure Service Accounts for Pods.

Grant permissions to a ServiceAccount

You can use the built-in Kubernetesrole-based access control (RBAC)mechanism to grant the minimum permissions required by each service account.You create arole, which grants access, and thenbind the role to yourServiceAccount. RBAC lets you define a minimum set of permissions so that theservice account permissions follow the principle of least privilege. Pods thatuse that service account don't get more permissions than are required tofunction correctly.

For instructions, refer toServiceAccount permissions.

Cross-namespace access using a ServiceAccount

You can use RBAC to allow service accounts in one namespace to perform actionson resources in a different namespace in the cluster. For example, consider ascenario where you have a service account and Pod in thedev namespace andyou want your Pod to see Jobs running in themaintenance namespace. You couldcreate a Role object that grants permissions to list Job objects. Then,you'd create a RoleBinding object in themaintenance namespace to bind theRole to the ServiceAccount object. Now, Pods in thedev namespace can listJob objects in themaintenance namespace using that service account.

Assign a ServiceAccount to a Pod

To assign a ServiceAccount to a Pod, you set thespec.serviceAccountNamefield in the Pod specification. Kubernetes then automatically provides thecredentials for that ServiceAccount to the Pod. In v1.22 and later, Kubernetesgets a short-lived,automatically rotating token using theTokenRequestAPI and mounts the token as aprojected volume.

By default, Kubernetes provides the Podwith the credentials for an assigned ServiceAccount, whether that is thedefault ServiceAccount or a custom ServiceAccount that you specify.

To prevent Kubernetes from automatically injectingcredentials for a specified ServiceAccount or thedefault ServiceAccount, set theautomountServiceAccountToken field in your Pod specification tofalse.

In versions earlier than 1.22, Kubernetes provides a long-lived, static tokento the Pod as a Secret.

Manually retrieve ServiceAccount credentials

If you need the credentials for a ServiceAccount to mount in a non-standardlocation, or for an audience that isn't the API server, use one of thefollowing methods:

  • TokenRequest API(recommended): Request a short-lived service account token from withinyour ownapplication code. The token expires automatically and can rotateupon expiration.If you have a legacy application that is not aware of Kubernetes, youcould use a sidecar container within the same pod to fetch these tokensand make them available to the application workload.
  • Token Volume Projection(also recommended): In Kubernetes v1.20 and later, use the Pod specification totell the kubelet to add the service account token to the Pod as aprojected volume. Projected tokens expire automatically, and the kubeletrotates the token before it expires.
  • Service Account Token Secrets(not recommended): You can mount service account tokens as KubernetesSecrets in Pods. These tokens don't expire and don't rotate. In versions prior to v1.24, a permanent token was automatically created for each service account.This method is not recommended anymore, especially at scale, because of the risks associatedwith static, long-lived credentials. TheLegacyServiceAccountTokenNoAutoGeneration feature gate(which was enabled by default from Kubernetes v1.24 to v1.26), prevented Kubernetes from automatically creating these tokens forServiceAccounts. The feature gate is removed in v1.27, because it was elevated to GA status; you can still create indefinite service account tokens manually, but should take into account the security implications.

Note:

For applications running outside your Kubernetes cluster, you might be consideringcreating a long-lived ServiceAccount token that is stored in a Secret. This allows authentication, but the Kubernetes project recommends you avoid this approach.Long-lived bearer tokens represent a security risk as, once disclosed, the tokencan be misused. Instead, consider using an alternative. For example, your externalapplication can authenticate using a well-protected private keyand a certificate,or using a custom mechanism such as anauthentication webhook that you implement yourself.

You can also use TokenRequest to obtain short-lived tokens for your external application.

Restricting access to Secrets (deprecated)

FEATURE STATE:Kubernetes v1.32 [deprecated]

Note:

kubernetes.io/enforce-mountable-secrets is deprecated since Kubernetes v1.32. Use separate namespaces to isolate access to mounted secrets.

Kubernetes provides an annotation calledkubernetes.io/enforce-mountable-secretsthat you can add to your ServiceAccounts. When this annotation is applied,the ServiceAccount's secrets can only be mounted on specified types of resources,enhancing the security posture of your cluster.

You can add the annotation to a ServiceAccount using a manifest:

apiVersion:v1kind:ServiceAccountmetadata:annotations:kubernetes.io/enforce-mountable-secrets:"true"name:my-serviceaccountnamespace:my-namespace

When this annotation is set to "true", the Kubernetes control plane ensures thatthe Secrets from this ServiceAccount are subject to certain mounting restrictions.

  1. The name of each Secret that is mounted as a volume in a Pod must appear in thesecrets field of thePod's ServiceAccount.
  2. The name of each Secret referenced usingenvFrom in a Pod must also appear in thesecretsfield of the Pod's ServiceAccount.
  3. The name of each Secret referenced usingimagePullSecrets in a Pod must also appear in thesecretsfield of the Pod's ServiceAccount.

By understanding and enforcing these restrictions, cluster administrators can maintain a tighter security profile and ensure that secrets are accessed only by the appropriate resources.

Authenticating service account credentials

ServiceAccounts use signedJSON Web Tokens (JWTs)to authenticate to the Kubernetes API server, and to any other system where atrust relationship exists. Depending on how the token was issued(either time-limited using aTokenRequest or using a legacy mechanism witha Secret), a ServiceAccount token might also have an expiry time, an audience,and a time after which the tokenstarts being valid. When a client that isacting as a ServiceAccount tries to communicate with the Kubernetes API server,the client includes anAuthorization: Bearer <token> header with the HTTPrequest. The API server checks the validity of that bearer token as follows:

  1. Checks the token signature.
  2. Checks whether the token has expired.
  3. Checks whether object references in the token claims are currently valid.
  4. Checks whether the token is currently valid.
  5. Checks the audience claims.

The TokenRequest API producesbound tokens for a ServiceAccount. Thisbinding is linked to the lifetime of the client, such as a Pod, that is actingas that ServiceAccount. SeeToken Volume Projectionfor an example of a bound pod service account token's JWT schema and payload.

For tokens issued using theTokenRequest API, the API server also checks thatthe specific object reference that is using the ServiceAccount still exists,matching by theunique ID of thatobject. For legacy tokens that are mounted as Secrets in Pods, the API serverchecks the token against the Secret.

For more information about the authentication process, refer toAuthentication.

Authenticating service account credentials in your own code

If you have services of your own that need to validate Kubernetes serviceaccount credentials, you can use the following methods:

The Kubernetes project recommends that you use the TokenReview API, becausethis method invalidates tokens that are bound to API objects such as Secrets,ServiceAccounts, Pods or Nodes when those objects are deleted. For example, if youdelete the Pod that contains a projected ServiceAccount token, the clusterinvalidates that token immediately and a TokenReview immediately fails.If you use OIDC validation instead, your clients continue to treat the tokenas valid until the token reaches its expiration timestamp.

Your application should always define the audience that it accepts, and shouldcheck that the token's audiences match the audiences that the applicationexpects. This helps to minimize the scope of the token so that it can only beused in your application and nowhere else.

Alternatives

What's next

Items on this page refer to third party products or projects that provide functionality required by Kubernetes. The Kubernetes project authors aren't responsible for those third-party products or projects. See theCNCF website guidelines for more details.

You should read thecontent guide before proposing a change that adds an extra third-party link.

Last modified November 19, 2024 at 10:53 PM PST:Address comments (3b8c927a3b)