How to create a Pod that uses non default service account using kubectl run command?

5/1/2019

I am trying to use the kubectl run command to create a Pod that uses a custom serviceaccount "svcacct1" instead of default serviceaccout. There seems to be no switch for providing a specific serviceaccount within the run command so leveraging --overrides switch to provide JSON as shown below.

kubectl run ng2 --image=nginx --namespace=test --overrides='{ "apiVersion": "apps/v1", "spec": { "serviceAccount": "svcacct1" , "serviceAccountName": "svcacct1" }  }' -o yaml

This does create the Pod (and a deployment) successfully but does not leverage the "svcacct1" and instead uses "default" as shown below (only relevant part of the output is shown)

> kubectl get po ng2-569d45c6b5-c9zhp -o yaml -n test

spec:
  containers:
  - image: nginx
    imagePullPolicy: Always
    name: ng2
    resources: {}
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: default-token-cpwjr
      readOnly: true
  dnsPolicy: ClusterFirst
  enableServiceLinks: true
  nodeName: minikube
  priority: 0
  restartPolicy: Always
  schedulerName: default-scheduler
  securityContext: {}
  serviceAccount: default
  serviceAccountName: default
  terminationGracePeriodSeconds: 30 

Also, the account does exist in the correct namespace.

> kubectl get serviceaccount svcacct1 -o yaml -n test

apiVersion: v1
kind: ServiceAccount
metadata:
  creationTimestamp: "2019-05-01T11:56:52Z"
  name: svcacct1
  namespace: test
  resourceVersion: "632061"
  selfLink: /api/v1/namespaces/test/serviceaccounts/svcacct1
  uid: 3573ffc6-6c08-11e9-9c81-0800270172ea
secrets:
- name: svcacct1-token-q9ksc

It is not clear what is missing for this to work?

-- Razi
kubectl
kubernetes

1 Answer

5/1/2019

At least in kubectl 1.14 there is such a flag:

$ kubectl version --client
Client Version: version.Info{Major:"1", Minor:"14", GitVersion:"v1.14.0", GitCommit:"641856db18352033a0d96dbc99153fa3b27298e5", GitTreeState:"clean", BuildDate:"2019-03-26T00:04:52Z", GoVersion:"go1.12.1", Compiler:"gc", Platform:"darwin/amd64"}
$ kubectl run -h | grep -- "--serviceaccount"
      --serviceaccount='': Service account to set in the pod spec
-- Vasily Angapov
Source: StackOverflow