kubernetes secrets files to environment variables

11/13/2015

Update: Kubernetes supports adding secrets directly to environment variables now. See pod example on github


Original post:

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 https://blog.oestrich.org/2015/09/kubernetes-secrets-to-env-file/

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

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.

How would I write a script to do this?

-- rwilson04
bash
kubernetes
ruby

1 Answer

11/16/2015

I noted your use case in the feature request for exposing secrets as environment variables: https://github.com/kubernetes/kubernetes/issues/4710

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".

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

There may be more elegant ways to do this.

-- briangrant
Source: StackOverflow