Google Cloud Build 中的环境变量

Posted

技术标签:

【中文标题】Google Cloud Build 中的环境变量【英文标题】:Environment variables in Google Cloud Build 【发布时间】:2019-01-05 18:05:50 【问题描述】:

我们希望从 Bitbucket Pipelines 迁移到 Google Cloud Build 以测试、构建和推送 Docker 映像。

我们如何在没有 CryptoKey 的情况下使用环境变量?例如:

- printf "https://registry.npmjs.org/:_authToken=$NPM_TOKEN\nregistry=https://registry.npmjs.org" > ~/.npmrc

【问题讨论】:

【参考方案1】:

要在构建步骤的args 部分中使用环境变量,您需要:

"a shell to resolve environment variables with $$"(如示例代码here中提到的) 您还需要小心使用引号(使用单引号)

有关这两点的更详细说明,请参阅下面的中断。

虽然 David Bendory 也链接到的 Using encrypted resources 文档(并且您可能基于您的假设)展示了如何使用通过 secretEnv 指定的加密环境变量来执行此操作,但这不是必需的,它适用于正常的环境变量也是。

在您的具体情况下,您需要将构建步骤修改为如下所示:

# you didn't show us which builder you're using - this is just one example of
# how you can get a shell using one of the supported builder images

- name: 'gcr.io/cloud-builders/docker'
  entrypoint: 'bash'
  args: ['-c', 'printf "https://registry.npmjs.org/:_authToken=%s\nregistry=https://registry.npmjs.org" $$NPM_TOKEN > ~/.npmrc']

注意%s 在要格式化的字符串中的用法以及环境变量如何作为参数传递给printf。我不知道有一种方法可以将环境变量值直接包含在格式字符串中。

您也可以使用echo,如下所示:

args: ['-c', 'echo "https://registry.npmjs.org/:_authToken=$$NPM_TOKEN\nregistry=https://registry.npmjs.org" > ~/.npmrc']


详细解释:

我在顶部的第一个点实际上可以一分为二:

    您需要一个 shell 来解析环境变量,并且 您需要转义 $ 字符,以便 Cloud Build 不会尝试在此处执行替换

如果您不这样做 2. 您的构建将失败并出现以下错误:合并替换和验证构建时出错:验证构建时出错:模板“NPM_TOKEN”中的键不是有效的内置替换

您应该通读Substituting variable values 文档并确保您了解其工作原理。然后你需要意识到你没有在这里执行替换,至少不是 Cloud Build 替换。您要求 shell 执行替换。

在这种情况下,2. 实际上是您从 Substituting variable values 文档中获得的唯一有用信息($$ 计算为文字字符 $)。

如果您经常使用 shell,我在顶部的第二点可能很明显。 these two questions 很好地解释了需要使用单引号的原因。基本上:“您需要使用单引号来防止在调用 shell 中发生插值。”

【讨论】:

【参考方案2】:

听起来你想使用加密的秘密:https://cloud.google.com/cloud-build/docs/securing-builds/use-encrypted-secrets-credentials

【讨论】:

正如我所提到的,我不想使用 KMS,加密的秘密。但似乎没有它是不可能的。 我可能不理解你的问题;请注意,您可以将环境变量传递到构建步骤中 (env):cloud.google.com/cloud-build/docs/api/reference/rest/v1/… 我认为@NuruddinIminokhunov 希望能够做类似的事情:` - name: 'gcr.io/cloud-builders/npm', env: NPM_TOKEN: 'my_token'`

以上是关于Google Cloud Build 中的环境变量的主要内容,如果未能解决你的问题,请参考以下文章

如何通过 Google Cloud Build 中的步骤设置环境或替换变量?

如何在 Google App Engine 标准环境中使用 Google Cloud Build 或其他方法设置环境变量?

Google Cloud Build 不会替换 cloudbuild.yaml 的机密部分中的值

将 env 变量从 Google 的 Secret Manager 加载到在 Google Cloud Run 上运行但未通过 Cloud Build 部署的 Docker 容器中?

在 Google Cloud Function 中设置环境变量

为啥任何项目上的 git push 都会触发 Google Cloud Build(GitHub 应用程序)中的构建?