<p>We have a set of deployments (sets of pods) that are all using same docker image. Examples:</p>

<ul>
<li>web api</li>
<li>web admin</li>
<li>web tasks worker nodes</li>
<li>data tasks worker nodes</li>
<li>...</li>
</ul>

<p>They all require a set of environment variables that are common, for example location of the database host, secret keys to external services, etc. They also have a set of environment variables that are not common.</p>

<p>Is there anyway where one could either:</p>

<ol>
<li>Reuse a template where environment variables are defined</li>
<li>Load environment variables from file and set them on the pods</li>
</ol>

<p>The optimal solution would be one that is namespace aware, as we separate the test, stage and prod environment using kubernetes namespaces.</p>

<p>Something similar to dockers env_file would be nice. But I cannot find any examples or reference related to this. The only thing I can find is setting env via secrets, but that is not clean, way to verbose, as I still need to write all environment variables for each deployment.</p>

<p>You can <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/#create-a-configmap" rel="nofollow noreferrer">create a ConfigMap</a> with all the common <code>key:value</code> pairs of env variables.</p>
<p>Then you can reuse the configmap to declare all the values of <code>configMap</code> as environment in <code>Deployment</code>.</p>
<p>Here is an example taken from <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/#configure-all-key-value-pairs-in-a-configmap-as-pod-environment-variables" rel="nofollow noreferrer">kubernetes official docs</a>.</p>
<p>Create a ConfigMap containing multiple key-value pairs.</p>
<pre><code>apiVersion: v1
kind: ConfigMap
metadata:
  name: special-config
  namespace: default
data:
  SPECIAL_LEVEL: very
  SPECIAL_TYPE: charm
</code></pre>
<p>Use envFrom to define all of the ConfigMap’s data as Pod environment variables. The key from the ConfigMap becomes the environment variable name in the Pod.</p>
<pre><code>apiVersion: v1
kind: Pod
metadata:
  name: test-pod
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ &quot;/bin/sh&quot;, &quot;-c&quot;, &quot;env&quot; ]
      envFrom:
      - configMapRef:
          name: special-config # All the key-value pair will be taken as environment key-value pair
      env:
      - name: uncommon
        value: &quot;uncommon value&quot;
  restartPolicy: Never
</code></pre>
<p>You can specify uncommon env variables in <code>env</code> field.</p>
<p>Now, to verify if the environment variables are actually available, see the logs.</p>
<pre><code>$ kubectl logs -f test-pod 
KUBERNETES_PORT=tcp://10.96.0.1:443
SPECIAL_LEVEL=very
uncommon=uncommon value
SPECIAL_TYPE=charm
...
</code></pre>
<p>Here, it is visible that all the provided environments are available.</p>
