## Intro

Kubernetes Service Accounts are the foundation for how workloads authenticate to the Kubernetes API and external services. When they are misconfigured, applications fail with cryptic errors, deployments stall, and security postures weaken. As an administrator or developer, you need to diagnose these issues quickly and apply safe, repeatable fixes.

This guide walks through the most common Service Account administration errors: missing accounts, incorrect secrets, token mount problems, insufficient RBAC permissions, and namespace pitfalls. For each error, you will see the typical symptoms, root cause analysis, and concrete commands to verify and resolve the issue. We focus on practical, copy-paste examples with expected outputs so you can build confidence and avoid common traps.

By the end, you will have a structured troubleshooting approach and an operations checklist to keep your clusters healthy.

## Version and Environment Inventory

Before changing any Service Account configuration, document your environment. This prevents version-specific surprises and ensures your fixes are compatible with your cluster's authorization mode and API capabilities.

Prerequisites to verify:

- **Kubernetes version**: Service Account token behavior changed significantly in v1.24 (legacy token creation stopped by default). Check with:

```bash
kubectl version --short
```

Expected output:

```
Client Version: v1.27.3
Kustomize Version: v5.0.1
Server Version: v1.27.3
```

- **Authorization mode**: RBAC must be enabled for Service Account permissions to work as expected. Inspect the API server flags:

```bash
kubectl cluster-info dump | grep authorization-mode
```

Expected output (may vary):

```
"--authorization-mode=Node,RBAC"
```

- **Cluster topology**: Identify namespaces and existing Service Accounts you plan to touch.

```bash
kubectl get serviceaccounts --all-namespaces
```

Expected output (abbreviated):

```
NAMESPACE     NAME       SECRETS   AGE
default       default    0         10d
kube-system   default    0         10d
myapp         myapp-sa   0         5d
```

- **User privileges**: Ensure your own kubeconfig context has permission to manage Service Accounts, Roles, RoleBindings, and Secrets in the target namespaces. Use `kubectl auth can-i --list` to verify.

- **Workload type**: Note whether the workloads using the Service Account are Deployments, StatefulSets, DaemonSets, or Pods. This affects how you update pod specs.

Record these details. A shared runbook or note helps teammates reproduce the environment.

## Safe Configuration Path

When modifying Service Accounts, follow least-privilege principles and make incremental changes. Avoid cluster-wide edits until a single namespace proves stable.

### Step 1: Create or Update a Service Account

Start with a simple Service Account definition. Use a YAML file and apply it with `kubectl apply` for idempotency.

Example file `sa.yaml`:

```yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: myapp-sa
  namespace: myapp
automountServiceAccountToken: true
```

Apply it:

```bash
kubectl apply -f sa.yaml
```

Expected output:

```
serviceaccount/myapp-sa created
```

If the Service Account already exists, `apply` will update it. To inspect:

```bash
kubectl get sa myapp-sa -n myapp -o yaml
```

Expected output (abbreviated):

```yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: myapp-sa
  namespace: myapp
secrets:
- name: myapp-sa-token-xxxxx
automountServiceAccountToken: true
```

### Step 2: Assign RBAC Permissions

A Service Account alone grants no API access. Create a Role scoped to the namespace and bind it.

Example `role.yaml`:

```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: myapp
  name: pod-reader
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "list", "watch"]
```

Apply:

```bash
kubectl apply -f role.yaml
```

Then bind to the Service Account with `rolebinding.yaml`:

```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: read-pods
  namespace: myapp
subjects:
- kind: ServiceAccount
  name: myapp-sa
  namespace: myapp
roleRef:
  kind: Role
  name: pod-reader
  apiGroup: rbac.authorization.k8s.io
```

Apply:

```bash
kubectl apply -f rolebinding.yaml
```

Expected output:

```
rolebinding.rbac.authorization.k8s.io/read-pods created
```

### Step 3: Attach Service Account to Workload

Ensure your Deployment's pod template references `serviceAccountName`.

Patch an existing Deployment:

```bash
kubectl set serviceaccount deployment myapp-deploy myapp-sa -n myapp
```

Expected output:

```
deployment.apps/myapp-deploy serviceaccount updated
```

This triggers a rolling update. Monitor with:

```bash
kubectl rollout status deployment/myapp-deploy -n myapp
```

Expected output:

```
deployment "myapp-deploy" successfully rolled out
```

### Step 4: Use Token Request API Instead of Static Secrets

For applications running inside the cluster, rely on projected service account tokens. These are short-lived, automatically rotated, and safer than manually created Secrets.

Do not manually create a Secret unless you have a specific legacy need. If you must create a token manually (pre-1.24 style), be aware that from Kubernetes v1.24, you need to create the Secret with the annotation `kubernetes.io/service-account.name` and set type to `kubernetes.io/service-account-token`.

Example `token-secret.yaml`:

```yaml
apiVersion: v1
kind: Secret
metadata:
  name: myapp-sa-token
  namespace: myapp
  annotations:
    kubernetes.io/service-account.name: myapp-sa
type: kubernetes.io/service-account-token
```

Apply and then retrieve the token:

```bash
kubectl apply -f token-secret.yaml
kubectl get secret myapp-sa-token -n myapp -o jsonpath='{.data.token}' | base64 -d
```

Expected output (a JWT string):

```
eyJhbGciOiJSUzI1NiIsImtpZCI6IiJ9...
```

Prefer the TokenRequest API via `kubectl create token` for temporary tokens:

```bash
kubectl create token myapp-sa -n myapp --duration=1h
```

Expected output:

```
<some JWT>
```

## Verification and Diagnostics

After applying changes, verify that the Service Account works as intended. Use these checks to catch misconfigurations early.

### Verify Service Account Exists and is Correct

Check the Service Account:

```bash
kubectl get sa myapp-sa -n myapp -o yaml
```

Look for `secrets` field (if manually attached) or just the name. For token mounting, ensure `automountServiceAccountToken` is not set to `false` unless intended.

### Verify Pod Uses the Service Account

Inspect a running pod:

```bash
kubectl get pod -n myapp -l app=myapp -o jsonpath='{.items[0].spec.serviceAccountName}'
```

Expected output:

```
myapp-sa
```

Check the mounted token file inside the pod (if you have exec access):

```bash
kubectl exec -n myapp <pod-name> -- ls -l /var/run/secrets/kubernetes.io/serviceaccount
```

Expected output:

```
total 0
lrwxrwxrwx 1 root root 13 Feb 10 12:00 ca.crt -> ..data/ca.crt
lrwxrwxrwx 1 root root 16 Feb 10 12:00 namespace -> ..data/namespace
lrwxrwxrwx 1 root root 21 Feb 10 12:00 token -> ..data/token
```

### Test API Access from Within the Pod

Use `kubectl exec` to run a `curl` command to the API server using the mounted token:

```bash
kubectl exec -n myapp <pod-name> -- sh -c 'curl -s -H "Authorization: Bearer $(cat /var/run/secrets/kubernetes.io/serviceaccount/token)" https://kubernetes.default.svc/api/v1/namespaces/myapp/pods --cacert /var/run/secrets/kubernetes.io/serviceaccount/ca.crt'
```

Expected output if RBAC is correct: JSON list of pods or a forbidden error if permissions insufficient.

### Check RBAC Permissions with kubectl auth can-i

Simulate the Service Account's permissions:

```bash
kubectl auth can-i list pods --as=system:serviceaccount:myapp:myapp-sa -n myapp
```

Expected output:

```
yes
```

For a verb not allowed:

```bash
kubectl auth can-i create pods --as=system:serviceaccount:myapp:myapp-sa -n myapp
```

Expected output:

```
no
```

### Inspect Events and Logs

If a pod fails to start due to Service Account issues, check events:

```bash
kubectl describe pod -n myapp <pod-name>
```

Look for lines like:

```
Warning  FailedMount  2m (x5 over 3m)  kubelet  MountVolume.SetUp failed for volume "kube-api-access-xxxxx" : failed to fetch token: serviceaccounts "myapp-sa" not found
```

Also check API server logs if you have access, but often the pod events are sufficient.

## Common Pitfalls and How to Avoid Them

Service Account misconfigurations are often caused by a handful of recurring mistakes. Understanding why they happen helps you prevent them proactively.

### 1. Forgetting to Create the Service Account

**Why it happens:** The pod spec references `serviceAccountName: myapp-sa`, but the Service Account was never created in that namespace. This often occurs when copying manifests between environments or when a CI/CD pipeline omits a step.

**How to avoid:** Use a single source of truth for all Service Account definitions and include them in your deployment pipeline. Run a pre-deployment check:

```bash
kubectl get sa myapp-sa -n myapp
```

If it fails, create it before deploying the workload.

**Recovery:** Create the missing Service Account and then delete the stuck pod to trigger a reschedule, or restart the Deployment:

```bash
kubectl apply -f sa.yaml
kubectl rollout restart deployment/myapp-deploy -n myapp
```

### 2. Neglecting RBAC Role Binding

**Why it happens:** Even with a Service Account and token, the API server denies requests if no Role or ClusterRole is bound. This mistake is common because the pod starts successfully, but the application later logs `403 Forbidden` errors.

**How to avoid:** Always define and bind a Role immediately after creating a Service Account. Use `kubectl auth can-i` in your CI pipeline to validate permissions.

**Recovery:** Create the missing Role and RoleBinding, then wait for the application to retry or restart it. No pod restart is strictly required, as RBAC changes take effect immediately.

### 3. Disabling Token Mounting Unintentionally

**Why it happens:** Setting `automountServiceAccountToken: false` on the Service Account or pod spec prevents the token from being mounted. This is often done for security hardening but forgotten when the application later needs API access.

**How to avoid:** Document which workloads require API access and audit `automountServiceAccountToken` settings. Use `kubectl get sa <name> -o yaml` to inspect the field.

**Recovery:** Set `automountServiceAccountToken: true` on the Service Account or pod, then restart the pod:

```bash
kubectl patch sa myapp-sa -n myapp -p '{"automountServiceAccountToken": true}'
kubectl rollout restart deployment/myapp-deploy -n myapp
```

### 4. Manual Token Secrets Expiring or Missing

**Why it happens:** In Kubernetes v1.24+, Service Account token Secrets are no longer created automatically. Teams that follow older tutorials may waste time looking for a Secret that does not exist. Even when manually created, those tokens may expire or become invalid.

**How to avoid:** Use the TokenRequest API (`kubectl create token`) for short-lived credentials, or rely on projected tokens automatically mounted in pods. Avoid manual Secrets unless strictly necessary.

**Recovery:** If a manually created token Secret is invalid, delete it and generate a new one via `kubectl create token`. Ensure the application uses the projected token instead.

### 5. Namespace Mismatch Between Service Account and Pod

**Why it happens:** A Service Account is namespaced, and a pod can only reference a Service Account in its own namespace. Copying manifests across namespaces without updating references leads to `serviceaccounts "myapp-sa" not found` errors.

**How to avoid:** Use consistent naming conventions and avoid hardcoding namespaces in manifests. Parameterize your deployment files with a templating tool like Helm or Kustomize.

**Recovery:** Correct the namespace in the pod spec to match the Service Account's namespace, or recreate the Service Account in the pod's namespace.

### 6. Overly Broad Permissions

**Why it happens:** To quickly fix a `Forbidden` error, someone grants `cluster-admin` to a Service Account. This creates a security risk and violates least privilege.

**How to avoid:** Start with the minimum verbs and resources required, then expand only if necessary. Use tools like `kubectl-who-can` or `kubeaudit` to audit permissions.

**Recovery:** Replace the broad binding with a narrowly scoped Role and RoleBinding, then test with `kubectl auth can-i --as=system:serviceaccount:myapp:myapp-sa -n myapp`.

## Failure Modes and Recovery

Even with careful configuration, failures happen. Knowing how to roll back and recover safely is essential.

### Common Failure Modes

- **ServiceAccount not found**: Occurs when the pod spec references a Service Account that does not exist in the namespace. Symptom: pod stuck in `ContainerCreating` with `FailedMount` event.
  - Fix: Create the Service Account or correct the spelling.

- **Insufficient RBAC permissions**: The application logs show `Forbidden` errors when calling the API. Even if the Service Account exists and token mounts, the Role/RoleBinding may be missing or too restrictive.
  - Fix: Review and adjust RBAC rules. Use `kubectl auth can-i` to test.

- **Token not mounted**: If `automountServiceAccountToken` is set to `false` on the Service Account or pod spec, the token file will be absent. Symptoms: app cannot authenticate, sees empty token.
  - Fix: Set `automountServiceAccountToken: true` or remove the field (default is true).

- **Legacy secret token expired or invalid**: Manually created tokens might have expired or be malformed. Since v1.24, Secrets for tokens are not automatically created, so old instructions fail.
  - Fix: Use TokenRequest API or create proper Secret with correct annotations.

- **Namespace mismatch**: The Service Account exists in a different namespace than the pod, or the RoleBinding references the wrong namespace for the subject.
  - Fix: Ensure all resources are in the same namespace as the workload. Cross-namespace Service Account usage is not allowed for pods.

### Safe Rollback Procedures

If a change breaks your application, revert to the previous working configuration. Because we used version-controlled YAML files and `kubectl apply`, you can reapply the previous manifest or use `rollout undo`.

Revert a Deployment to previous revision:

```bash
kubectl rollout undo deployment/myapp-deploy -n myapp
```

Expected output:

```
deployment.apps/myapp-deploy rolled back
```

Revert a Service Account or RBAC change: Apply the previous YAML from your git history, or use `kubectl apply -f previous.yaml`.

Delete a manually created token Secret if it caused issues:

```bash
kubectl delete secret myapp-sa-token -n myapp
```

Then ensure the application relies on projected tokens.

### Recovery Checks After Rollback

- Verify pod status returns to `Running`.
- Re-run `kubectl auth can-i` as the Service Account to confirm permissions are as expected.
- Check application logs to ensure no more authentication errors.

## Operations Checklist

Use this checklist for ongoing management and to prevent common errors.

| Check | Command or Action | Expected Result |
|---|---|---|
| Verify Service Account exists | `kubectl get sa <name> -n <ns>` | Shows AGE and SECRETS |
| Confirm pod uses correct SA | Inspect pod spec or `kubectl get pod -o json` | `serviceAccountName` matches |
| Test RBAC permissions | `kubectl auth can-i <verb> <resource> --as=system:serviceaccount:<ns>:<sa> -n <ns>` | `yes` or `no` as designed |
| Check token mount | `kubectl exec <pod> -- ls /var/run/secrets/kubernetes.io/serviceaccount/token` | File exists |
| Review events for failures | `kubectl describe pod <pod> -n <ns>` | No FailedMount warnings |
| Validate token if manually created | Decode token and inspect expiry | Token is valid JWT |
| Ensure least privilege | Review Role and RoleBinding rules regularly | Minimum required verbs/resources |
| Monitor for forbidden errors in app logs | Query logs for `403` or `Forbidden` | No unexpected denials |

Preventive practices:

- Prefer projected tokens over static Secrets.
- Use `automountServiceAccountToken: false` for pods that do not need API access to reduce attack surface.
- Regularly audit Service Accounts and their permissions with tools like `kubectl-who-can` or `kubeaudit`.
- Document each Service Account's purpose and ownership. For each Service Account, assign a single accountable owner (for example, `myapp-sa` is owned by the Application Team Lead, reviewed quarterly).

## Conclusion

Kubernetes Service Account errors are often caused by simple mismatches: missing account, wrong namespace, insufficient RBAC, or token mounting issues. By following a systematic approach -- inventory your environment, configure safely, verify with observable checks, and know recovery steps -- you can resolve most issues quickly and prevent recurrence.

Remember to test changes in a non-production namespace first, keep your YAML manifests under version control, and use least-privilege RBAC. The operations checklist in this guide serves as a handy reference for you and your team.

Now that you have the tools, tackle that failing pod with confidence.