vovan
vovan

Reputation: 1520

How to prevent escaping of an ENV variable passed into ruby application in docker container

keys.env contains private key:

KEY="-----BEGIN PRIVATE KEY-----\nBADANBgkqhki......xjiWsX7Qjoh8XH8nAECgYEAkCNIy1eICdUUt6HgV\nnEGKpwDETJTIJdmW5MlOzsURI/RSnE2Qas/k758isGLaA4m9dZJoxuP/pCfwcvLj\nwmjVBPdTTNF6ADgor6ZVIp6os5wIIurZH7f8yXaggTEyk5r8K6qxz9t/D\n4FaPDsZ2icg0N5i2y/2Sa0w=\n-----END PRIVATE KEY-----\n"

(The value of KEY should be enclosed in quotes because it contains \n)

docker-compose.yml contains env_file parameter:

version: '2'

services:
  testenv:
    image: ruby:2.4-slim  
    env_file:
      - ./keys.env

I run the container with ruby app:

docker-compose run testenv

and try to use ENV['KEY'] variable:

irb(main):001:0> ENV['KEY']
=> "\"-----BEGIN PRIVATE KEY-----\\nBADANBgkqhki......xjiWsX7Qjoh8XH8nAECgYEAkCNIy1eICdUUt6HgV\\nnEGKpwDETJTIJdmW5MlOzsURI/RSnE2Qas/k758isGLaA4m9dZJoxuP/pCfwcvLj\\nwmjVBPdTTNF6ADgor6ZVIp6os5wIIurZH7f8yXaggTEyk5r8K6qxz9t/D\\n4FaPDsZ2icg0N5i2y/2Sa0w=\\n-----END PRIVATE KEY-----\\n\""

The variable is escaped, but I need clean private_key.

I have not found the answer in the Docker documentations.

I see two working solutions, but none seems to me right.

  1. Store private_key in the .env file encoded and without quotes. A module in the app will decode this value.
  2. Unescape value in the app (like this Best way to escape and unescape strings in Ruby?)

Is there a way to solve this problem with built-in capabilities of Docker?

Upvotes: 4

Views: 1833

Answers (1)

Robert
Robert

Reputation: 36803

You've hit a known issue of docker:

https://github.com/moby/moby/issues/11443

Sorry for the inconvenience but I would rather go the conservative route on this one :( The problem can be solved with echo -e like you mentioned and I think the benefit of keeping env-file simple is higher. I'm going to close this issue, but feel free to continue the discussion and speak up if you disagree.

The equivalent in ruby of that echo -e is replacing literal '\n' with a real newline:

ENV['KEY'].gsub('\n', "\n")

And remove the double quotes, leave it as this:

KEY=-----BEGIN PRIVATE KEY-----\nBADANBgkqhki......xjiWsX7Qjoh8XH8nAECgYEAkCNIy1eICdUUt6HgV\nnEGKpwDETJTIJdmW5MlOzsURI/RSnE2Qas/k758isGLaA4m9dZJoxuP/pCfwcvLj\nwmjVBPdTTNF6ADgor6ZVIp6os5wIIurZH7f8yXaggTEyk5r8K6qxz9t/D\n4FaPDsZ2icg0N5i2y/2Sa0w=\n-----END PRIVATE KEY-----\n

But I recommend to just mount a file:

version: '2'

services:
  testenv:
    image: ruby:2.4-slim  
    volumes:
      - ./keys.pem:/root/keys.pem

Then do a simple file read from ruby.

Upvotes: 2

Related Questions