Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get environment variables in a cloud function

I have a Cloud Function in GCP that queries BigQuery in a specific project/environment. As I have multiple environments I would like to get the current project/environment of the cloud function. This is so that I can access BigQuery in the corresponding environment. Of course I could just hardcode the project_id, but I would like to do this programmatically.

According to Google environment variables are set automatically. But when I try to access those I cannot find any of them.

For instance I have tried the following, which gives me none of the env. var listed by Google.

print(os.environ)

Anyone managed to access environment variables at runtime?

like image 306
Jostein Sortland Avatar asked Aug 05 '20 08:08

Jostein Sortland


People also ask

How do I show all environment variables in Linux?

To list all the environment variables, use the command " env " (or " printenv "). You could also use " set " to list all the variables, including all local variables.


3 Answers

Those environment variables you are referring to only applies to python 3.7, the second section on that page (https://cloud.google.com/functions/docs/env-var#nodejs_10_and_subsequent_runtimes) states :

All languages and runtimes other than those mentioned in the previous section will use this more limited set of predefined environment variables.

This means the GCP_PROJECT is no longer set with 3.8 (at least for now).

like image 119
redorkulated Avatar answered Oct 16 '22 17:10

redorkulated


For Python 3.8 there is a workaround:

import google.auth

_, project_id = google.auth.default()
print(project_id)
like image 4
redmode Avatar answered Oct 16 '22 17:10

redmode


This is working fine

import os
os.environ.get('GCP_PROJECT')
like image 2
Vikram Shinde Avatar answered Oct 16 '22 18:10

Vikram Shinde