Docker & Kubernetes
ServiceAccount
Learn Pod identity with a ServiceAccount.
ServiceAccount
A ServiceAccount is the identity pods (not humans) use to access the API. Every namespace has a default ServiceAccount, and a pod uses it if none is specified. If an application will access the API (e.g. an operator listing pods), it gets its own ServiceAccount and only the permissions it needs:
kubectl create serviceaccount api -n dev
spec:
serviceAccountName: api
containers:
- name: api
image: api:1.0
Kubernetes automatically mounts a short-lived token into the pod at /var/run/secrets/kubernetes.io/serviceaccount/token.
Granting a ServiceAccount permissions
A ServiceAccount is bound in a RoleBinding as a kind: ServiceAccount subject; on the command line it is written as namespace:name. The permission is tested with the identity system:serviceaccount:namespace:name:
kubectl create rolebinding api-pod-okuyucu --role=pod-okuyucu --serviceaccount=dev:api -n dev
kubectl auth can-i list pods -n dev --as system:serviceaccount:dev:api
yes
Exercise Give the app an identity
Write three commands: create the api ServiceAccount in dev; create a RoleBinding api-pod-okuyucu in dev giving the pod-okuyucu role to the dev:api ServiceAccount; query the permission to list pods in dev as system:serviceaccount:dev:api.
Show example solution
kubectl create serviceaccount api -n dev
kubectl create rolebinding api-pod-okuyucu --role=pod-okuyucu --serviceaccount=dev:api -n dev
kubectl auth can-i list pods -n dev --as system:serviceaccount:dev:api
Test yourself
-
What is recommended for an application that never accesses the API?
- Giving the default ServiceAccount edit
- Doing nothing
- Not mounting the token with automountServiceAccountToken: false
- Granting cluster-admin
Show answer
Not mounting the token with automountServiceAccountToken: false — An unused token opens a door for an attacker if the pod is compromised.
-
Specify which ServiceAccount the pod uses.
spec:
____: api
Show answer
spec:
serviceAccountName: api
-
Match.
- ServiceAccount
- Pod identity
- default
- If unspecified
- dev:api
- namespace:name
- automountServiceAccountToken
- Token mounting
Next lesson: Verbs and resources