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

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

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

<pre><code>kubectl get serviceaccount
</code></pre>

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

<p>I essentially need to have something like </p>

<pre><code>serviceAccountName: {test:-default}
</code></pre>

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

<p>As long as you want run this validation inside the cluster, the only way would be to use <a href="https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/" rel="nofollow noreferrer">MutatingAdmissionWebhook</a>. </p>

<p>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.</p>

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

<p>Here is an <a href="https://github.com/banzaicloud/admission-webhook-example/blob/master/webhook.go" rel="nofollow noreferrer">example</a> of the weebhook, which validates and sets custom labels.</p>

<p>More info about <a href="https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/" rel="nofollow noreferrer">Admission Controller Webhooks</a></p>
