<p>Is it possible write write an existing environment variable into a file from a Kubernetes deployment.yaml file?</p>
<p>The background: I've already parsed a json containing secrets. Now, I'd like to store that secret in a local file.</p>
<p>So far, I've tried something like this:</p>
<pre><code>      lifecycle:
        postStart:
          exec:
            command: [&quot;/bin/sh&quot;, &quot;-c&quot;],
            args: [&quot;echo $PRIVATE_KEY &gt; /var/private.key&quot;] 
</code></pre>
<p>( I've setup /var/ as an empty writeVolume. )</p>
<p>Or perhaps there is a completely different way to do this, such as storing the secret in it's own, separate secret?</p>

<p>Rather than using <code>postStart</code> , I'd suggest you use an <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" rel="nofollow noreferrer">init container</a>, the <code>postStart</code> hook doesn't guarantee that it will be executed before the container <code>ENTRYPOINT</code>.</p>
<p>You can define your environment variables in your deployment manifest, by setting static values or referencing a <code>configMap</code> or <code>secret</code>. Your init container would run a bash script that writes the content of each variable to a file.</p>
<p>A second approach would be to mount a <code>configMap</code> as a volume inside your pod, e.g.:</p>
<pre><code>apiVersion: v1
kind: ConfigMap
metadata:
  name: special-config
  namespace: default
data:
  SPECIAL_LEVEL: very
  SPECIAL_TYPE: charm
</code></pre>
<pre><code>apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ &quot;/bin/sh&quot;, &quot;-c&quot;, &quot;ls /etc/config/&quot; ]
      volumeMounts:
      - name: config-volume
        mountPath: /etc/config
  volumes:
    - name: config-volume
      configMap:
        # Provide the name of the ConfigMap containing the files you want
        # to add to the container
        name: special-config
  restartPolicy: Never
</code></pre>
<p>That would create two files inside <code>/etc/config</code>, named as the key defined in your <code>configMap</code> with the content of its value.</p>
