set `serviceAccountName` to `default` in case it does not exist

7/16/2019

So a typical k8s deployment file that I'm woking on looks like this:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  labels:
    ...
  name: ${service-name}
spec:
  replicas: 1
  strategy:
    ...
  template:
    metadata:
       ...
    spec:
      serviceAccountName: test
      ...

the goal is to create multiple services who have access to the same serviceAccount. This structure works fine when test exists in

kubectl get serviceaccount

The question is how can I set serviceAccountName to default serviceAccount if test does not exist in the namespace (for any reason)? I don't wanna fail the deployment

I essentially need to have something like

serviceAccountName: {test:-default}

P.S. clearly I can assign a variable to serviceAccountName and parse the yaml file from outside, but wanted to see if there's a better option

-- Mahyar
kubernetes
kubernetes-deployment

1 Answer

7/17/2019

As long as you want run this validation inside the cluster, the only way would be to use MutatingAdmissionWebhook.

This will intercepts requests matching the rules defined in MutatingWebhookConfiguration before presisting into etcd. MutatingAdmissionWebhook executes the mutation by sending admission requests to webhook server. Webhook server is just plain http server that adhere to the API.

Thus, you can validate if the service account exists and set default sa if it's not.

Here is an example of the weebhook, which validates and sets custom labels.

More info about Admission Controller Webhooks

-- A_Suh
Source: StackOverflow