Google Cloud Build 中的环境变量

2024-01-08

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

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

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

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

  • “使用 $$ 解析环境变量的 shell”(如示例代码中所述here https://cloud.google.com/cloud-build/docs/securing-builds/use-encrypted-secrets-credentials#example_build_request_using_an_encrypted_variable)
  • 并且您还需要小心引号的使用(使用单引号)

请参阅下面的中断以获取对这两点的更详细解释。

虽然使用加密资源 https://cloud.google.com/cloud-build/docs/securing-builds/use-encrypted-secrets-credentialsDavid Bendory 也链接到的文档(您可能基于您的假设)展示了如何使用通过指定的加密环境变量来执行此操作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']


详细解释:

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

  1. 你需要一个 shell 来解析环境变量,并且
  2. 你需要逃离$字符,以便 Cloud Build 不会尝试在此处执行替换

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

您应该通读替换变量值 https://cloud.google.com/cloud-build/docs/configuring-builds/substitute-variable-values文档并确保您了解其工作原理。然后你需要意识到你是not在这里执行替换,至少不是 Cloud Build 替换。您要求 shell 执行替换。

在这种情况下,2.实际上是您从替换变量值 https://cloud.google.com/cloud-build/docs/configuring-builds/substitute-variable-values文档(即$$计算结果为字面字符$).

如果您习惯于经常使用 shell,那么我在顶部的第二点可能是显而易见的。需要使用单引号的原因很好地解释了these https://stackoverflow.com/questions/26167803/how-does-bin-bash-c-differ-from-executing-a-command-directly two https://stackoverflow.com/questions/1711970/i-cant-seem-to-use-the-bash-c-option-with-arguments-after-the-c-option-st问题。基本上:“您需要使用单引号来防止调用 shell 中发生插值。”

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Google Cloud Build 中的环境变量 的相关文章

随机推荐