Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 512 of 8028. Security and ObservabilityFree lesson

Utilizing Default ServiceAccount Security Best Practices

Identify risks associated with the default ServiceAccount and learn how to disable automatic token mounting for enhanced security.

In this lesson, you will learn how to secure your cluster by disabling the automatic mounting of authentication tokens for the default ServiceAccount.

The Risk of the Default ServiceAccount

By default, every Namespace in Kubernetes contains a ServiceAccount named default. When you deploy a Pod without specifying a serviceAccountName, Kubernetes automatically assigns it this default account. Crucially, the cluster also automatically mounts an API token for that ServiceAccount into every Pod at /var/run/secrets/kubernetes.io/serviceaccount/token.

If your application is compromised, an attacker can use this token to query the Kubernetes API. While the default account typically has limited permissions, it can often list other resources, gather information about the cluster environment, or discover internal service endpoints. Leaving these tokens mounted by default violates the principle of least privilege, especially for pods that don't need to interact with the Kubernetes API at all.

Disabling Automatic Token Mounting

To enhance your security posture, you should disable the automatic mounting of tokens for the default ServiceAccount. You can achieve this by patching the ServiceAccount to set automountServiceAccountToken to false.

You can apply this change directly via kubectl:

kubectl patch serviceaccount default -p '{"automountServiceAccountToken": false}'

Alternatively, you can include this configuration in your YAML manifests to ensure new namespaces or custom ServiceAccounts follow the same security standard:

apiVersion: v1
kind: ServiceAccount
metadata:
  name: restricted-sa
automountServiceAccountToken: false

By setting this to false, the Kubernetes controller manager will no longer inject the sensitive API token into the Pod's filesystem. If your application legitimately requires access to the Kubernetes API, you should create a specific, dedicated ServiceAccount with the minimum required Role or ClusterRole permissions, rather than relying on the loosely scoped default account. This proactive step significantly reduces the blast radius of a potential container breakout or application compromise.

Key Takeaway: Disable automountServiceAccountToken on your ServiceAccounts to prevent unnecessary API tokens from being exposed to your Pods, thereby enforcing the principle of least privilege.