【问题标题】:How to set env variable in local development for google cloud functions?如何在本地开发中为谷歌云功能设置环境变量?
【发布时间】:2022-01-10 07:05:02
【问题描述】:

我正在尝试在我需要设置一些环境变量的本地系统上运行云功能。我正在关注 docs 用于环境和本地开发 docs

我正在尝试通过以下命令运行我的项目:

node node_modules/@google-cloud/functions-framework --target=syncingredients --env-vars-file=.env.yaml

我的.env.yaml 的样子:

API_KEY: key
AUTH_DOMAIN: project.firebaseapp.com

【问题讨论】:

  • 我认为使用 npm init 创建一个 package.json 文件,使用您的内容创建 index.js 文件,使用 npm install @google-cloud/functions-framework 安装函数框架,将启动脚本添加到 package.json,并通过命令传递配置-line 参数,例如:"start":"functions-framework --target=helloWorld --trigger-http --env-vars-file ./.env.yaml"(其中 .env.yaml 设置了您的环境变量),然后 npm start 也可以实现相同的效果
  • 不,不是@PriyashreeBhadra,如果你查看github.com/GoogleCloudPlatform/functions-framework-nodejs/…,你会发现它不是

标签: google-cloud-platform google-cloud-functions environment-variables


【解决方案1】:

函数框架似乎不支持 --env-vars-file (https://github.com/GoogleCloudPlatform/functions-framework-nodejs/issues/38)

我会推荐relymd-djk建议的解决方法:

前置要求:

npm install env-cmd 
npm install yaml2json

修改 package.json 脚本部分:

"scripts": {
    "start":"yaml2json .env.yaml >.env.json && env-cmd -r ./.env.json functions-framework --target=syncingredients",
    "deploy": "gcloud functions deploy myFunction --entry-point syncingredients  --trigger-http --runtime nodejs16  --env-vars-file ./.env.yaml"
}

运行函数:

npm start

【讨论】:

  • 谢谢。刚刚赞成并喜欢您的回答,但我会为我的项目选择 dotenv。
【解决方案2】:

感谢 ClumsyPuffin 强调它不是可用的功能,所以我选择了 dotenv

把文件改成.env:

API_KEY="key"
AUTH_DOMAIN="project.firebaseapp.com"

并使用以下命令在本地运行函数

node -r dotenv/config node_modules/@google-cloud/functions-framework --target=syncingredients

【讨论】:

    【解决方案3】:
    1. env-cmd 安装为开发依赖项
    npm i env-cmd --save-dev
    
    1. 更新package.json
    {
      "name": "google-cloud-function",
      "version": "0.0.1",
      "dependencies": {
        "@google-cloud/functions-framework": "^3.0.0",
      },
      "scripts": {
        "start": "env-cmd functions-framework --target=googleCloudFunction"
      },
      "devDependencies": {
        "env-cmd": "^10.1.0"
      }
    }
    
    1. 在根目录下创建.env
    ENV_VARIABLE_HAHA="hahahah"
    ENV_VARIABLE_FOO="fooo"
    
    1. index.js
    'use strict';
    
    console.log(process.env);
    
    exports.googleCloudFunction= async (req, res) => {
      console.info('googleCloudFunction started...');
      try {
        const {ENV_VARIABLE_HAHA, ENV_VARIABLE_FOO} = process.env;
        console.log(ENV_VARIABLE_HAHA, ENV_VARIABLE_FOO);
    
        console.info('googleCloudFunction finished.');
    
        res.status(200).send(process.env);
      } catch (err) {
        console.error(err.message);
        console.error('googleCloudFunctionfailed.');
    
        res.status(500).send(err.message);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-30
      • 2019-10-21
      • 1970-01-01
      • 2015-05-30
      • 2019-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多