Create an Environment Variable from a Private Key

We all know that we shouldn’t hard code our sensitive information in our Docker images. Often though, we may need a private key to authenticate.
If you are using docker-compose you can add environment variables to the container without having them in the image by using:



and it will use the values of those environment variables from the shell which runs docker-compose.

The question is how do you put the contents of a key file with multiple lines into a single line variable?

It really is quite easy if you just process the file with awk and append \\n after each line.
You have to tidy up a bit with sed to eliminate the final \\n

#!/usr/bin/env bash
export $name=”$(awk ‘BEGIN{}{out=out$0”\n”}END{print out}’ $file| sed ‘s/\n$//‘)”


You just source the file supplying the envar name and the file.

source keytoenvar.sh RSA_KEY ~/.ssh/id_rsa


I have only used this with RSA keys but it should work with any key file that follows a similar format. Of course, if the api you are calling is expecting a file name rather than the contents you would have to have your code copy the value of the envar to a file but that is simple.

Hopefully this will encourage you to keep the sensitive information out of your Docker image.