且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Google App Engine 标准环境中使用 Google Cloud Build 或其他方法设置环境变量?

更新时间:2022-05-24 09:07:39

这里有一个 教程,了解如何在您的云构建(触发器)设置中安全地存储环境变量并将它们导入您的应用.

Here is a tutorial on how to securely store env vars in your cloud build (triggers) settings and import them into your app.

基本上分为三个步骤:

  1. 将环境变量添加到构建触发器设置之一的变量"部分

  1. Add your env vars to the 'variables' section in one of your build trigger settings

在构建触发器中添加变量的位置的屏幕截图

按照约定,在构建触发器中设置的变量必须以下划线 (_) 开头

By convention variables set in the build trigger must begin with an underscore (_)

配置 cloudbuild.yaml(在代码示例的第二步)以从构建触发器读取变量,将它们设置为 env vars,并将所有 env vars 写入本地.env 文件

Configure cloudbuild.yaml (on the second step in the code example) to read in variables from your build trigger, set them as env vars, and write all env vars in a local .env file

couldbuild.yaml(如下)添加到你的项目根目录

Add couldbuild.yaml (below) to your project root directory

steps:
- name: node:10.15.1
  entrypoint: npm
  args: ["install"]
- name: node:10.15.1
  entrypoint: npm
  args: ["run", "create-env"]
  env:
    - 'MY_SECRET_KEY=${_MY_SECRET_KEY}'
- name: "gcr.io/cloud-builders/gcloud"
  args: ["app", "deploy"]
timeout: "1600s"

create-env 脚本添加到 package.json

"scripts": {
  "create-env": "printenv > .env"
},

  1. 将 .env 中的环境变量读取到您的应用 (config.js)

  1. Read env vars from .env to your app (config.js)

安装 dotenv 包

Install dotenv package

npm i dotenv -S

config.js 添加到您的应用

// Import all env vars from .env file
require('dotenv').config()

export const MY_SECRET_KEY = process.env.MY_SECRET_KEY

console.log(MY_SECRET_KEY) // => Hello

完成!现在,您可以通过触发云构建来部署您的应用,并且您的应用将可以访问环境变量.

Done! Now you may deploy your app by triggering the cloud build and your app will have access to the env vars.