21

How to Use Newlines in an Environment Variable File for Docker

 2 years ago
source link: https://www.dannyguo.com/blog/how-to-use-newlines-in-an-environment-variable-file-for-docker/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to Use Newlines in an Environment Variable File for Docker

April 19, 2022  ·  176 words  ·  ~1 minute to read

When you run a Docker container, you can pass environment variables to the run command. However, the --env-file option has a limitation in that it doesn’t handle newline characters. See this GitHub issue and this comment on a separate issue.

This can be problematic if you need newlines for something like a public or private key for public-key cryptography. I tried adding double quotes around the value and using \n for the newlines:

FOO=bar
PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nFOO\nBAR\nBAZ\n-----END PRIVATE KEY-----"

But that didn’t work, using single quotes didn’t work, and actually breaking the value across multiple lines in my .env file didn’t work either. As a workaround, I found that I could detect the situation and modify the value in code. For a Node.js server, I did this:

let PRIVATE_KEY = process.env.PRIVATE_KEY;
if (PRIVATE_KEY?.startsWith(`"`)) {
    PRIVATE_KEY =
        PRIVATE_KEY.replaceAll(`"`, ``).replaceAll(`\\n`, `\n`);
}

So I removed the double quotes and replaced every occurrence of a literal backslash (the \\ is necesssary for escaping the backslash) followed by a n with a newline character. This worked for my use case.



Follow me on Twitter or subscribe to my free newsletter or RSS feed for future posts.

Found an error or typo? Feel free to open a pull request on GitHub.



Twitter GitHub Email

You can encrypt messsages with my GPG key if you'd like.

© 2022 Danny Guo

This content is licensed under CC BY-NC-SA 4.0 and hosted on GitHub.

As an Amazon Associate I earn from qualifying purchases.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK