Can you have two containers in a pod have different service accounts?

I have a use case where I have two containers, my sidecar container, and my user’s user specified container. I don’t want to give either more permission than they need. My sidecar needs an elevated permission, that the user container does not need. The converse can also be tru.

I believe this is possible, thought not recommended, to have two service accounts. This can be done by setting spec.automountServiceAccountToken to false. Then you specifiy two volumes (one for each service account’s secret token) for the pod, and only one volume mount per container (for the two different service accounts). Then you have two containers in one pod, but with different Kubernetes API permissions.

One thing I do not understand is, if this is possible, then why are automountServiceAccountToken and serviceAccountName under .spec not under .spec.containers? Does serviceAccountName only do something if automountServiceAccountToken is true? Does the pods serviceAccountName have any effects I’m not aware of?

Have you got any idea on this? can we use two service account in same pod? I need one service account for the init container and another for the main container.

I believe this is possible by following the below steps:

  1. defining automountServiceAccountToken to false
  2. Create two different service account now
  3. Mount the tokens from two diff service account to volumes of that pod
  4. Create volumemounts to whichever the container needs the corresponding SA with the secret value to the location /var/run/secrets/kubernetes.io/serviceaccount/token