CodeBlanks Logo Icon CodeBlanks

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

Practice 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.

Starter code

terminal
# buraya yaz

Sample solution

terminal
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

Expected output

serviceaccount/api created
rolebinding.rbac.authorization.k8s.io/api-pod-okuyucu created
yes

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 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 Correct answer
  • Granting cluster-admin

Explanation: An unused token opens a door for an attacker if the pod is compromised.

2 Specify which ServiceAccount the pod uses.

Question
    spec:
      ____: api
Answer
    spec:
      serviceAccountName: api

Explanation: serviceAccountName is in the pod spec.

3 Match.

Term Meaning
ServiceAccount Pod identity
default If unspecified
dev:api namespace:name
automountServiceAccountToken Token mounting

All lessons in Advanced