在 Google Cloud Build 中使用 Google Cloud Secret 作为环境变量
Using Google Cloud Secret as environment variables in Google Cloud Build
我正在使用 Cloud Build 将我的 Node 应用程序部署到 Google Cloud 运行,我想 运行 在构建期间进行一些测试。我的测试需要一些环境变量,所以我一直在关注 this guide 来实现这一点。
指南做了如下说明:
Note: To use the secret in an environment variable, you need to prefix
the variable name with an underscore "_" and escape the value using
'('. For example: _VARIABLE_NAME=$(cat password.txt) && echo -n
\)_VARIABLE_NAME.
但是,我不太确定如何实现它。
我在 cloudbuild.yaml
.
中尝试了以下操作
- id: Execute tests
name: node
args: ['_VAR_ONE=$(cat var-one.txt)', '_VAR_TWO=$(cat var-two.txt)', 'jest -V']
其中returns以下:Error: Cannot find module '/workspace/_VAR_ONE=$(cat var-one.txt)'
。
我还尝试了上面提到的一些转义变体,但它们导致了同样的错误。
将秘密作为环境变量放入我的代码中的最佳方法是什么?
另外,如果我需要使用多个环境变量,是否最好将 Cloud KMS 与 .env
文件一起使用?
谢谢!
您似乎错误地使用了 node
图片提供的 entrypoint
。您实际上是在 运行 执行命令:
node _VAR_ONE=$(cat var-one.txt) _VAR_TWO=$(cat var-two.txt) jest -V
说句题外话,说这个模式在Node中不起作用,你需要先指定环境变量before调用node
,例如VAR_ONE=$(cat foo.txt) VAR_TWO=bar node run test
总之,我觉得你想要运行的是:
_VAR_ONE=$(cat var-one.txt) _VAR_TWO=$(cat var-two.txt) jest -V
这就是我们将如何做到这一点 - 假设您在上一步中将机密内容写到文件 var-one.txt
和 var-two.txt
中 - 以下是方法您将在 node
步骤中使用它,这只是在 运行 从命令行执行命令时使用环境变量的标准方式:
- id: Execute tests
name: node
entrypoint: '/bin/bash'
args:
'-c',
'_VAR_ONE=$(cat var-one.txt) _VAR_TWO=$(cat var-two.txt) jest -V'
]
您需要确保在节点环境中使用指定的变量(即 process.env._VAR_ONE
或 process.env._VAR_TWO
)。我认为您不需要在此处添加 _
字符前缀,但我尚未对其进行测试以确认这一点。你可以尝试上面的方法,我认为它应该会让你走得更远。
我正在使用 Cloud Build 将我的 Node 应用程序部署到 Google Cloud 运行,我想 运行 在构建期间进行一些测试。我的测试需要一些环境变量,所以我一直在关注 this guide 来实现这一点。
指南做了如下说明:
Note: To use the secret in an environment variable, you need to prefix the variable name with an underscore "_" and escape the value using '('. For example: _VARIABLE_NAME=$(cat password.txt) && echo -n \)_VARIABLE_NAME.
但是,我不太确定如何实现它。
我在 cloudbuild.yaml
.
- id: Execute tests
name: node
args: ['_VAR_ONE=$(cat var-one.txt)', '_VAR_TWO=$(cat var-two.txt)', 'jest -V']
其中returns以下:Error: Cannot find module '/workspace/_VAR_ONE=$(cat var-one.txt)'
。
我还尝试了上面提到的一些转义变体,但它们导致了同样的错误。
将秘密作为环境变量放入我的代码中的最佳方法是什么?
另外,如果我需要使用多个环境变量,是否最好将 Cloud KMS 与 .env
文件一起使用?
谢谢!
您似乎错误地使用了 node
图片提供的 entrypoint
。您实际上是在 运行 执行命令:
node _VAR_ONE=$(cat var-one.txt) _VAR_TWO=$(cat var-two.txt) jest -V
说句题外话,说这个模式在Node中不起作用,你需要先指定环境变量before调用node
,例如VAR_ONE=$(cat foo.txt) VAR_TWO=bar node run test
总之,我觉得你想要运行的是:
_VAR_ONE=$(cat var-one.txt) _VAR_TWO=$(cat var-two.txt) jest -V
这就是我们将如何做到这一点 - 假设您在上一步中将机密内容写到文件 var-one.txt
和 var-two.txt
中 - 以下是方法您将在 node
步骤中使用它,这只是在 运行 从命令行执行命令时使用环境变量的标准方式:
- id: Execute tests
name: node
entrypoint: '/bin/bash'
args:
'-c',
'_VAR_ONE=$(cat var-one.txt) _VAR_TWO=$(cat var-two.txt) jest -V'
]
您需要确保在节点环境中使用指定的变量(即 process.env._VAR_ONE
或 process.env._VAR_TWO
)。我认为您不需要在此处添加 _
字符前缀,但我尚未对其进行测试以确认这一点。你可以尝试上面的方法,我认为它应该会让你走得更远。