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?
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.
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).
For Python 3.8 there is a workaround:
import google.auth
_, project_id = google.auth.default()
print(project_id)
This is working fine
import os
os.environ.get('GCP_PROJECT')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With