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

Managing Pod Identity With ServiceAccounts

Create and manage dedicated ServiceAccounts to provide distinct identities for applications running inside your Kubernetes pods.

In this lesson, you will learn how to assign distinct, granular identities to your applications running within Kubernetes pods using ServiceAccounts.

Why Pod Identity Matters

By default, every pod in a namespace runs under the default ServiceAccount. If your application needs to interact with the Kubernetes API—perhaps to watch for new Custom Resources or update a Status subresource—it needs an identity. Relying on the default account is a security risk because it often carries excessive or unnecessary permissions. Instead, you should create dedicated ServiceAccounts to follow the principle of least privilege.

Creating and Assigning a ServiceAccount

A ServiceAccount acts as the "user" identity for your process inside the pod. You define it as a standard Kubernetes resource:

apiVersion: v1
kind: ServiceAccount
metadata:
  name: controller-manager-sa
  namespace: my-app-namespace

Once created, you associate this identity with your pod (or the pod template in your Deployment or Operator spec) by setting the serviceAccountName field. When the pod starts, Kubernetes automatically mounts a token representing this identity into the container.

Linking Identity to Permissions

The ServiceAccount itself has no permissions; it is merely an identity. To make it functional, you must bind it to a Role or ClusterRole using a RoleBinding or ClusterRoleBinding.

For example, if you are building an Operator that needs to manage your custom resources, you would:

  1. Create the ServiceAccount (as shown above).
  2. Create a Role that defines the rules for accessing your CRDs.
  3. Create a RoleBinding that maps the ServiceAccount to that Role.

When your application code uses the Kubernetes client library, it will automatically look for the mounted token associated with the ServiceAccount. This allows your pods to perform only the specific actions you have explicitly granted them, ensuring that your infrastructure remains secure even if an individual application component is compromised. By decoupling the identity from the pod specification, you gain modular control over your application's security posture.

Key Takeaway: Always create a dedicated ServiceAccount for each application component and use RoleBindings to grant only the minimum permissions required for its specific tasks.