我正在为 Cloud Build 设置环境变量(它们不必加密)。
env.sh
export GCP_PROJECT_ID=example
export GCP_KMS_KEYRING=example-secrets
export GCP_KMS_KEYNAME=example-identity
export GCP_KMS_ROLE=roles/cloudkms.cryptoKeyDecrypter
export GCP_KMS_KEY_ID=projects/$GCP_PROJECT_ID/locations/global/keyRings/$GCP_KMS_KEYRING/cryptoKeys/$GCP_KMS_KEYNAME
cloudbuild.yaml
steps:
# 1 Install Dependencies
- name: 'python'
id: Pip install
args: ['pip3', 'install', '-r', 'requirements.txt', '--user']
# 2 Set env variables for its execution
- name: 'ubuntu'
args: ['bash', 'scripts/env.sh']
# 3 Run Tests
- name: 'python'
args: ['python3', '-m', 'pytest', 'functions/test/']
运行步骤 2 无法正确设置这些。运行脚本时没有出现错误,但在稍后的测试中,当我尝试从 os.env 获取 GCP_KMS_KEY_ID 时,出现错误。我知道我可以在运行测试步骤下设置 env:
,但我的项目需要从文件加载 env。
设置环境变量的最佳实践是什么?
最佳答案
您还可以为整个build设置环境变量和替换,而不仅仅是构建步骤。对于您的变量,我建议使用替换和环境变量的组合。
steps:
- name: 'python'
entrypoint: 'bash'
args:
- '-c'
- |
# subs must being with _
echo $_NAME
echo $_GREETING
# env vars called with double $
echo $$MESSAGE
- name: 'ubuntu'
args: ['bash', '-c', 'echo $$MESSAGE']
substitutions:
_NAME: sam
_GREETING: hello
options:
env:
- MESSAGE=$_GREETING, $_NAME!
从你的例子来看,它可以工作
substitutions:
_GCP_PROJECT_ID: example
_GCP_KMS_KEYRING: example-secrets
_GCP_KMS_KEYNAME: example-identity
_GCP_KMS_ROLE: roles/cloudkms.cryptoKeyDecrypter
options:
env:
- GCP_KMS_KEY_ID=projects/$_GCP_PROJECT_ID/locations/global/keyRings/$_GCP_KMS_KEYRING/cryptoKeys/$_GCP_KMS_KEYNAME
关于python - 使用文件将环境变量加载到 Google Cloud Build,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56589979/