Service Accounts
ServiceAccounts provide identities for processes running inside Pods. Unlike user accounts (which are for humans), ServiceAccounts are namespaced Kubernetes resources managed directly by the cluster.
The Default ServiceAccount
Every namespace has a default ServiceAccount created automatically. Pods that do not specify a ServiceAccount use this one.
# View the default ServiceAccount
kubectl get serviceaccount default -n default
# See all ServiceAccounts in a namespace
kubectl get sa -n kube-system
Creating a ServiceAccount
# Create a ServiceAccount imperatively
kubectl create serviceaccount app-sa -n development
# Verify it was created
kubectl get sa app-sa -n development -o yaml
Or declaratively:
apiVersion: v1
kind: ServiceAccount
metadata:
name: app-sa
namespace: development
automountServiceAccountToken: false
Setting automountServiceAccountToken: false prevents the token from being mounted into Pods automatically, which is a security best practice when the Pod does not need to call the Kubernetes API.
Using a ServiceAccount in a Pod
apiVersion: v1
kind: Pod
metadata:
name: my-app
namespace: development
spec:
serviceAccountName: app-sa
containers:
- name: app
image: my-app:latest
The Pod will use the app-sa identity when making API calls to the cluster.
Granting RBAC Permissions to a ServiceAccount
A ServiceAccount has no permissions by default. Use a RoleBinding to grant access:
# Give the ServiceAccount read access to pods
kubectl create role pod-reader \
--verb=get,list,watch \
--resource=pods \
-n development
kubectl create rolebinding app-sa-pod-reader \
--role=pod-reader \
--serviceaccount=development:app-sa \
-n development
The --serviceaccount flag format is namespace:name.
Verifying ServiceAccount Permissions
# Check what the ServiceAccount can do
kubectl auth can-i list pods \
--as=system:serviceaccount:development:app-sa \
-n development
# Output: yes
Key Takeaways
- Every namespace has a
defaultServiceAccount used by Pods that do not specify one - Disable automatic token mounting when API access is not needed
- ServiceAccounts need explicit RBAC bindings to have any permissions
- Use the
namespace:nameformat when referencing ServiceAccounts in bindings