How to set env variable in local development for google cloud functions?

Viewed 1092

I'm trying to run cloud function on my local system for which I need to set some env variables. I'm following docs for env and for local development docs.

I'm trying to run my project via the following command:

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

Where my .env.yaml looks like:

API_KEY: key
AUTH_DOMAIN: project.firebaseapp.com
3 Answers

Seems like --env-vars-file aren't supported with functions framework (https://github.com/GoogleCloudPlatform/functions-framework-nodejs/issues/38)

I would recommend the workaround suggested by relymd-djk:

pre-req:

npm install env-cmd 
npm install yaml2json

modifying the package.json scripts section with:

"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"
}

to run the function:

npm start

Thanks to ClumsyPuffin for highlighting that it isn't an available feature so I went for dotenv

Changed the file to .env:

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

And used the following command to run the function locally

node -r dotenv/config node_modules/@google-cloud/functions-framework --target=syncingredients
  1. Install env-cmd as dev dependendy
npm i env-cmd --save-dev
  1. Update 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. Create .env in root directory
ENV_VARIABLE_HAHA="hahahah"
ENV_VARIABLE_FOO="fooo"
  1. In 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);
  }
}
Related