Mastering Kubernetes Service Accounts with kubectl

In Kubernetes, service accounts are the key to granting pods and processes controlled permissions within the cluster. With kubectl, you can create, inspect, and manage these accounts with precision. They define the identity a workload uses to interact with the API server and other resources.

A service account is bound to a namespace. By default, new pods use the namespace’s default service account unless you specify another. This default account often has minimal privileges, which is good for security. For elevated or specialized access, create custom service accounts and pair them with the right roles.

Creating a Service Account
To create one, run:

kubectl create serviceaccount my-service-account --namespace my-namespace

This writes a resource into the namespace. Kubernetes also creates a secret containing a token tied to the service account.

Assigning Roles to a Service Account
With RBAC (Role-Based Access Control), assign permissions:

kubectl create rolebinding my-binding \
 --role=my-role \
 --serviceaccount=my-namespace:my-service-account \
 --namespace my-namespace

Use roles for namespace-level permissions, cluster roles for cluster-wide. Always bind the least privilege needed.

Viewing Service Accounts
List them with:

kubectl get serviceaccounts --namespace my-namespace

Inspect details:

kubectl describe serviceaccount my-service-account --namespace my-namespace

Linking a Pod to a Service Account
In a pod spec:

apiVersion: v1
kind: Pod
metadata:
 name: my-pod
spec:
 serviceAccountName: my-service-account
 containers:
 - name: app
   image: my-image

The pod now runs with that account’s identity and permissions.

Security Considerations
Review token usage. Rotate or delete unused tokens. Limit access with fine-grained roles. Never mount unnecessary secrets into pods. Monitor for anomalies in API requests made under each account’s token.

Mastering kubectl service accounts keeps access predictable, auditable, and secure. It’s one of the simplest ways to harden your cluster while maintaining agility.

See this live in minutes with hoop.dev — connect, create, and manage service accounts effortlessly.