使用 docker 中的 build-arg 创建 json 文件

Use build-arg from docker to create json file

我有一个 docker 构建命令,我在 Jenkins 中 运行 执行 shell

docker build -f ./fastlane.dockerfile \
  -t fastlane-test \
  --build-arg PLAY_STORE_CREDENTIALS=$(cat PLAY_STORE_CREDENTIALS) \
  .

PLAY_STORE_CREDENTIALS 是使用托管文件保存在 Jenkins 中的 JSON 文件。然后,在我的 Dockerfile 中,我有

ARG PLAY_STORE_CREDENTIALS
ENV PLAY_STORE_CREDENTIALS=$PLAY_STORE_CREDENTIALS
WORKDIR /app/packages/web/android/fastlane/PlayStoreCredentials
RUN touch play-store-credentials.json
RUN echo $PLAY_STORE_CREDENTIALS >> ./play-store-credentials.json
RUN cat play-store-credentials.json

cat 注销空行或什么都不注销。

PLAY_STORE_CREDENTIALS的内容:

{
  "type": "...",
  "project_id": "...",
  "private_key_id": "...",
  "private_key": "...",
  "client_email": "...",
  "client_id": "...",
  "auth_uri": "...",
  "token_uri": "...",
  "auth_provider_x509_cert_url": "...",
  "client_x509_cert_url": "..."
}

知道问题出在哪里吗?

有没有实际上一个名为PLAY_STORE_CREDENTIALS的文件?如果是,并且是标准 JSON 文件,我希望您给定的命令行失败;如果文件包含 any 空格(这是 JSON 文件的典型特征),该命令应该会导致错误,例如...

"docker build" requires exactly 1 argument.

例如,如果我在 PLAY_STORE_CREDENTIALS 中有您问题的示例内容,我们会看到:

$ docker build -t fastlane-test --build-arg PLAY_STORE_CREDENTIALS=$(cat PLAY_STORE_CREDENTIALS) .
"docker build" requires exactly 1 argument.
See 'docker build --help'.

Usage:  docker build [OPTIONS] PATH | URL | -

...因为您没有正确引用您的论点。如果你采纳@β.εηοιτ.βε 的建议并引用 cat 命令,它似乎按预期构建:

$ docker build -t fastlane-test --build-arg PLAY_STORE_CREDENTIALS="$(cat PLAY_STORE_CREDENTIALS)" .

[...]

Step 7/7 : RUN cat play-store-credentials.json
 ---> Running in 29f95ee4da19
{ "type": "...", "project_id": "...", "private_key_id": "...", "private_key": "...", "client_email": "...", "client_id": "...", "auth_uri": "...", "token_uri": "...", "auth_provider_x509_cert_url": "...", "client_x509_cert_url": "..." }
Removing intermediate container 29f95ee4da19
 ---> b0fb95a9d894
Successfully built b0fb95a9d894
Successfully tagged fastlane-test:latest

您会注意到生成的文件不保留行结尾;那是因为您没有在 echo 语句中引用变量 $PLAY_STORE_CREDENTIALS 。你应该写成:

RUN echo "$PLAY_STORE_CREDENTIALS" >> ./play-store-credentials.json

最后,不清楚为什么要使用环境变量而不是仅使用 COPY 命令来传输此数据:

COPY PLAY_STORE_CREDENTIALS ./play-store-credentials.json

在上面的示例中,我使用以下 Dockerfile 进行测试:

FROM docker.io/alpine:latest

ARG PLAY_STORE_CREDENTIALS
ENV PLAY_STORE_CREDENTIALS=$PLAY_STORE_CREDENTIALS
WORKDIR /app/packages/web/android/fastlane/PlayStoreCredentials
RUN touch play-store-credentials.json
RUN echo $PLAY_STORE_CREDENTIALS >> ./play-store-credentials.json
RUN cat play-store-credentials.json

更新

这是一个使用 COPY 命令的示例,其中 PLAY_STORE_CREDENTIALS 构建参数的值是一个文件名:

FROM docker.io/alpine:latest

ARG PLAY_STORE_CREDENTIALS
WORKDIR /app/packages/web/android/fastlane/PlayStoreCredentials
COPY ${PLAY_STORE_CREDENTIALS} play-store-credentials.json
RUN cat play-store-credentials.json

如果我在名为 creds.json 的文件中有凭据,则可以像这样成功构建:

docker build -t fastlane-test --build-arg PLAY_STORE_CREDENTIALS=creds.json .