使用文件将环境变量加载到Google Cloud Build中

时间:2019-06-14 00:17:38

标签: python google-cloud-platform google-cloud-build

我正在为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设置不正确。运行脚本时没有错误,但是在稍后的测试中,当我尝试从GCP_KMS_KEY_ID抓取os.env时,出现了错误。我知道我可以在运行测试步骤下设置env:,但是我的项目需要从文件中加载环境。

设置环境变量的最佳实践是什么?

2 个答案:

答案 0 :(得分:1)

您还可以为整个构建设置环境变量和替代项,而不仅仅是构建步骤。对于您的变量,我建议同时使用替代变量和环境变量。

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

答案 1 :(得分:0)

将第2步合并到第3步怎么样?

args: ['bash', 'scripts/envs.h', '&&', 'python3', '-m', 'pytest', 'functions/test/']