Service accounts
- Version
- 1.37
- Review
- Draft
Summary#
A ServiceAccount gives a Pod an identity for API requests. Set spec.serviceAccountName to choose an account in the same namespace; otherwise the Pod uses default. Use RBAC bindings to give the account only the permissions it needs.
Syntax#
kubectl create serviceaccount NAME
kubectl create token NAME --duration=10m
spec:
serviceAccountName: worker
automountServiceAccountToken: false
Example#
Both Pods use the same account. The second disables the automatic credential mount. Each checks for the token file without printing its contents.
(
set -eu
ns="ref-serviceaccount-$$"
kubectl create namespace "$ns" >/dev/null
trap 'kubectl delete namespace "$ns" >/dev/null' EXIT
kubectl create serviceaccount -n "$ns" worker
for pod in default-mount disabled-mount; do
mount=
[ "$pod" != disabled-mount ] || mount=' automountServiceAccountToken: false'
kubectl apply -n "$ns" -f - <<YAML
apiVersion: v1
kind: Pod
metadata:
name: $pod
spec:
serviceAccountName: worker
$mount
restartPolicy: Never
containers:
- name: check
image: busybox:1.37
command:
- sh
- -c
- |
if [ -s /var/run/secrets/kubernetes.io/serviceaccount/token ]; then
echo 'token mounted'
else
echo 'no token mounted'
fi
YAML
kubectl wait -n "$ns" --for=jsonpath='{.status.phase}'=Succeeded "pod/$pod" --timeout=120s >/dev/null
kubectl logs -n "$ns" "$pod"
done
)
Expected output#
serviceaccount/worker created
pod/default-mount created
token mounted
pod/disabled-mount created
no token mounted
Common mistakes#
Set automountServiceAccountToken: false for Pods that do not need automatic API credentials. A Pod's setting takes precedence over the account's setting. A mounted token authenticates the Pod's API requests; authorization still depends on the account's permissions.
Version applicability#
The example targets Kubernetes 1.37. Automatically mounted, rotating tokens are stable since 1.22. Since 1.24, creating a ServiceAccount no longer creates a long-lived token Secret by default.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0