bash 使用 Dockerfile 设置多行环境变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50299617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:55:02  来源:igfitidea点击:

Set Multiline Environment Variable with Dockerfile

linuxbashdocker

提问by Daniel Rasmuson

I want to set a multiline environment variable in my Dockerfile.

我想在我的 Dockerfile 中设置一个多行环境变量。

Works through command line

通过命令行工作

If I pass in the environment variable through docker runeverything works.

如果我通过docker run一切正常传递环境变量。

CONFIG="port: 4466
databases:
  prod:
    connector: mysql
    active: true
    host: 33.333.333.333
    port: 3306
    user: root
    password: pass"
docker run --env CONFIG="$CONFIG" ubuntu:latest env | grep 'CONFIG'

Output (its only a single line because its interpreted as multiline variable)

输出(它只有一行,因为它被解释为多行变量)

CONFIG=port: 4466

Doesnt Work through dockerfile

不通过 dockerfile 工作

Dockerfile

文件

FROM ubuntu:latest
ENV CONFIG 'port: 4466\ndatabases:\n  prod:\n    connector: mysql\n    active: true\n    host: host\n    port: 3306\n    user: root\n    password: pass'

Build and run the docker image

构建并运行 docker 镜像

docker build -t multilinetest .
docker run multilinetest env | grep 'CONFIG'

Output

输出

CONFIG=port: 4466\ndatabases:\n  prod:\n    connector: mysql\n    active: true\n    host: host\n    port: 3306\n    user: root\n    password: pass

Expected

预期的

Both scenarios should store the same environment variable (I'm passing this environment variable into a 3rd party image that requires a multiline string)

两种场景都应该存储相同的环境变量(我将此环境变量传递到需要多行字符串的第 3 方图像中)

回答by Daniel Rasmuson

I was able to get this working by passing the multiline environment variable as a build arg to docker build.

我能够通过将多行环境变量作为构建参数传递给 docker build 来使其工作。

Dockerfile

文件

FROM ubuntu:latest
ARG CONFIG
ENV CONFIG $CONFIG

Build Command

构建命令

CONFIG="port: 4466
databases:
  prod:
    connector: mysql
    active: true
    host: 33.333.333.333
    port: 3306
    user: root
    password: pass"
docker build --build-arg CONFIG="$CONFIG" ubuntu:latest env | grep 'CONFIG'

回答by édouard Lopez

Escaping newline characters work fine.

转义换行符工作正常。

Dockerfile

文件

ENV BUILD_DEPENDENCIES apt-utils \
  curl \
  libc-dev \
  gcc \
  gnupg2

Output

输出

Step 8/48 : ENV BUILD_DEPENDENCIES apt-utils   curl   libc-dev   gcc   gnupg2
 ---> Running in 65b0ad105af4