首页 > 解决方案 > 如何在 Google Cloud 构建上传递替换变量以运行 dockerfile

问题描述

我在 Google Cloud 构建上设置了 Github 触发器。我已经有一个 dockerfile 来执行构建步骤。由于没有传递替换变量的规定,我尝试使用云构建配置文件(yaml)构建它,然后将路径传递给配置文件中的 dockerfile。

这是云构建配置文件,我需要传递 5 个变量供 Dockerfile 使用,yaml 文件如下所示:

steps:
- name: 'gcr.io/cloud-builders/docker'
  env:
  - 'ACCESS_TOKEN=$ACCESS_TOKEN'
  - 'BRANCH=$BRANCH'
  - 'UTIL_BRANCH=$UTIL_BRANCH'
  - 'ARG_ENVIRONMENT=$ARG_ENVIRONMENT'
  - 'ARG_PYTHON_SCRIPT=$ARG_PYTHON_SCRIPT'
  args:
  - build
  - "--tag=gcr.io/$PROJECT_ID/quickstart-image"
  - "--file=./twitter/dax/processing_scripts/Dockerfile"
  - .

当触发器运行构建时,我在 dockerfile 中的一个构建步骤中收到错误,指出该变量不可用。很明显,yaml文件中传递的环境变量并没有传递给Dockerfile进行消费。这就是我在触发页面上填充替换变量的方式 在此处输入图像描述

从出现错误的步骤 5 中粘贴构建代码,在此之前只是运行 apt-get update 命令:

Step 5/28 : RUN git config --global url."https://${ACCESS_TOKEN}:@github.com/".insteadOf "https://github.com/" && echo $(ACCESS_TOKEN)
 ---> Running in f7b94bc2a0d9

/bin/sh: 1: ACCESS_TOKEN: not found
Removing intermediate container f7b94bc2a0d9
 ---> 30965207dcec
Step 6/28 : ARG BRANCH
 ---> Running in 93e36589ac48
Removing intermediate container 93e36589ac48
 ---> 1d1508b1c1d9
Step 7/28 : RUN git clone https://github.com/my_repo45/twitter.git -b "${BRANCH}"
 ---> Running in fbeb93dbb113
Cloning into 'twitter'...
remote: Repository not found.
fatal: Authentication failed for 'https://github.com/my_repo45/twitter.git/'
The command '/bin/sh -c git clone https://github.com/my_repo45/twitter.git -b "${BRANCH}"' returned a non-zero code: 128
ERROR
ERROR: build step 0 "gcr.io/cloud-builders/docker" failed: step exited with non-zero status: 128```

Could anyone please point out what the issue and validate if the environment declaration is proper?

标签: dockergoogle-cloud-platformyamldockerfilegoogle-cloud-build

解决方案


您仍然需要将变量添加到docker build命令中。与您当前的情况一样,这些变量仅在云构建中可供您使用,而不是作为常规环境变量。下面概述了如何将这些变量传递给云构建的简化示例。请注意,您只能ARG在 dockerfile 中使用它,而不是ENV.

steps:
- name: 'gcr.io/cloud-builders/docker'
  env:
    - 'ACCESS_TOKEN=$ACCESS_TOKEN'
  args:
    - build
    - "--tag=gcr.io/$PROJECT_ID/quickstart-image"
    - "--file=./twitter/dax/processing_scripts/Dockerfile"
    - "--build-arg=ACCESS_TOKEN=${ACCESS_TOKEN}"
    - .

docker build另一种选择是在您的命令所在的同一构建步骤中导出环境变量:

steps:
- name: 'gcr.io/cloud-builders/docker'
  entrypoint: 'bash'
  env:
    - 'ACCESS_TOKEN=$ACCESS_TOKEN'
  args:
  - '-c'
  - |
    export ACCESS_TOKEN=${ACCESS_TOKEN}
    docker build \
      --tag=gcr.io/$PROJECT_ID/quickstart-image" \
      --file=./twitter/dax/processing_scripts/Dockerfile" \
      .

当然,您可以争论env此设置中是否仍需要该字段,我将由您决定。


推荐阅读