59

I'm using dotenv.

A Ruby gem to load environment variables from .env.

Is it possible to have multiline variables in my .env file?

e.g.

SOMETHING_CERTIFICATE="-----BEGIN CERTIFICATE-----
JSDFALDAFSSKLABVCXZLV2314IH4IHDFG9AYDF9DSSDF82QWEIWFHDSSD8SADF0=
-----END CERTIFICATE-----"

^ having the above just throws an error on that middle line, as if it's not part of the string and I'm trying to create an improperly formatted variable.

Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103
Mirror318
  • 11,875
  • 14
  • 64
  • 106
  • 1
    Did you tried "\n"? – Gokul Sep 11 '17 at 04:06
  • 1
    I did try "\n", it just came up in the error message automatically parsed to "\\n"—but that's because I tried to keep the whitespace newlines as well as the "\n"s. Putting it all on a single line with the "\n" worked, although it's not really what i wanted, it gets ugly for long strings. – Mirror318 Sep 12 '17 at 04:49

3 Answers3

54

According to the documentation

Multi-line values

If you need multiline variables, for example private keys, you can double quote strings and use the \n character for newlines:

PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nHkVN9…\n-----END DSA PRIVATE KEY-----\n"

Grant
  • 11,799
  • 13
  • 42
  • 47
Brian
  • 5,300
  • 2
  • 26
  • 32
  • To add to Brian answer. If you need to consume the PRIVATE_KEY in a config file for example, you can do something like this: ```signing_key "<<-EOL\n" + "#{ENV['PRIVATE_KEY']}".gsub("\\n","\n") + "EOL\n"``` – Gundam Meister Jul 13 '18 at 19:45
  • 76
    Answers containing “Did you try reading the documentation” do not deserve upvotes. – mxcl Aug 28 '21 at 14:26
  • 8
    `sed` version for the lazy: `cat id_rsa | sed -z -e 's/\n/\\n/g'` – davetapley Oct 23 '21 at 04:33
45

From the documentation Brian posted above:

Alternatively, multi-line values with line breaks are now supported for quoted values.

So the solution you sketched in your question is legit now!

SaturnFromTitan
  • 1,334
  • 14
  • 20
  • Weirdly, in a docker setup, me and my colleague (same OS) are getting inconsistencies with that. I Think it might be safest to add the newlines. – MrMesees Dec 01 '21 at 11:18
  • Fine for dotenv, I don't know for other scenarios https://github.com/bkeepers/dotenv#multi-line-values . – Eduardo Lucio Jan 03 '23 at 21:03
0

If you are using node, you could use fixedKey = key.replaceAll('\\n', '\n')

And in the .env
KEY=-----BEGIN PRIVATE KEY----- xY=\n.....3ZaWjyKJqy+xY=\n-----END PRIVATE KEY-----\n

Fix the error replaceAll is not a function changing the lib option under compilerOptions in the tsconfig.json for "es2021" if you are using typeScript.

Knemay
  • 350
  • 1
  • 6
  • 12