<p><strong>Update</strong>: Kubernetes supports adding secrets directly to environment variables now. See pod example on <a href="https://github.com/pmorie/kubernetes/blob/60cf252e8b8acfdc12f99e9b12ce0daa140b96f0/docs/user-guide/secrets/secret-env-pod.yaml" rel="nofollow">github</a></p>

<hr>

<p><strong>Original post</strong>:</p>

<p>I've been using files created by Kubernetes Secrets to store sensitive configs, but I always end up writing an extra layer into the containers or overriding the CMD to get the contents of the secret files into environment variables before running like normal. I'd like a bash script to do this for me. I found a ruby script that does something similar, but my ruby and bash skills aren't quite good enough to complete this. Here's the ruby script from <a href="https://blog.oestrich.org/2015/09/kubernetes-secrets-to-env-file/" rel="nofollow">https://blog.oestrich.org/2015/09/kubernetes-secrets-to-env-file/</a></p>

<pre><code>env = {}

Dir["#{ARGV[1]}/*"].each do |file|
  key = file.split("/").last
  key = key.gsub("-", "_").upcase
  env[key] = File.read(file).strip
end

File.open(ARGV[0], "w") do |file|
  env.each do |key, value|
    file.puts(%{export #{key}="#{value}"})
  end
end
</code></pre>

<p>With a bash script that does something similar to the above, it would be nice if it could be made generic, so that it checks if the directory exists, and if not (e.g. in a plain Docker environment), it will assume that the environment variables are already set by some other means.</p>

<p>How would I write a script to do this?</p>

<p>I noted your use case in the feature request for exposing secrets as environment variables:
<a href="https://github.com/kubernetes/kubernetes/issues/4710" rel="nofollow">https://github.com/kubernetes/kubernetes/issues/4710</a></p>

<p>It's mainly the quoting that makes this tricky in shell. The following worked for me interactively and should work in a script, but additional quoting would be needed if specified as an argument to "sh -c".</p>

<p>(ls -1 secretdir | while read var ; do echo export ${var}=$(cat secretdir/${var}) ; done; echo yourcommand) | sh -</p>

<p>There may be more elegant ways to do this.</p>
