且构网

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

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

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

这是

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

完成!现在,您可以通过触发云构建来部署应用程序,并且您的应用程序将可以访问env vars.

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