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

标签 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 无法正确设置这些。运行脚本时没有出现错误,但在稍后的测试中,当我尝试从 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/

相关文章:

python - Raspberry ALSA 声音输出/输入从机

python - Scikit - TF-IDF 空词汇表

python - 如何计算游戏板上孔的位置?

google-cloud-platform - 如何将 gke 节点更新为可抢占式?

google-cloud-build - 在特定区域和地区运行 Google Cloud Build?

maven - 如何在 google cloudbuild 上构建 quarkus 原生镜像

Python参数语法错误: invalid syntax

go - 带有google-cloud-datastore的liquibase示例

java - 如何查询 PubSub 项目主题/特定主题的 pubsub.topics.list 权限

google-cloud-platform - 如何部署使用google cloud build和Source Repository新推送的多个云函数?