简体   繁体   中英

Setting environment variables in Google Cloud Function

I'm building a small node.js application that accepts POST requests and would upload the data to Google BigQuery.

BigQuery requires the GOOGLE_APPLICATION_CREDENTIALS to be set, else BigQuery will just timeout. As explained here: https://cloud.google.com/docs/authentication/production

For example, making the query when the server was started as the following works as intended:

GOOGLE_APPLICATION_CREDENTIALS=path/to/credentials.json DEBUG=* bin/www

Making the query when the server was started as the following produces a timeout:

DEBUG=* bin/www

I've tried the following npm packages to set environment variables within the script:

"envs": "0.1.6",
"dotenv": "5.0.1"

And setting them as:

var envs = require('envs');
app.set('environment', envs('GOOGLE_APPLICATION_CREDENTIALS', 'path/to/credentials.json')); 

and

require('dotenv').config()

but alas...

Google Cloud function does not allow me to specify any environment variables, the script deployment logic is all behind the scenes. I've tried locating the config file in Google Cloud Console, and thought of setting it as a global environment variable, but I can't even locate it in that console.

Any ideas?

edit 08/14/2018

There was no option to set environment variables, but it's available now in beta mode. Just use the next command on deploy:

cloud beta functions deploy YOUR_FUNCTION_NAME --set-env-vars VAR1=foo,VAR2=bar FLAGS

edit 11/22/2018 (per Martin Omander's suggestion)

You can also set them from your node.js code if that makes sense for you: process.env.MY_VARIABLE = "it_works"

old answer (with resolution for the actual problem not related to env variables)

Unfortunately unlike AWS Lambda SCF doesn't support setting environment variables, at least in some obvious way.

But in your case you actually don't need that. You need GOOGLE_APPLICATION_CREDENTIALS on your local environment for testing, but on google cloud function it's enough to just set the project id in case you're using BigQuery npm

const BigQuery = require('@google-cloud/bigquery');

const projectId = 'project-id';

exports.testBigQuery = (req, res) => {

   const bigquery = new BigQuery({
       projectId: projectId,
   });


   bigquery
      .createDataset('test_set')
      .then(results => {
          const dataset = results[0];
          res.send(dataset.id);
      })
      .catch(err => {
          console.error('ERROR:', err);
      });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM