5

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?

4 Answers4

3

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).

redorkulated
  • 374
  • 1
  • 6
  • 13
2

For Python 3.8 there is a workaround:

import google.auth

_, project_id = google.auth.default()
print(project_id)
redmode
  • 4,454
  • 1
  • 21
  • 30
1

This is working fine

import os
os.environ.get('GCP_PROJECT')
Vikram Shinde
  • 852
  • 3
  • 16
  • Not working for me. When running print(os.environ) I do not get any of the environment variables that are set automatically by GCP. Are you running python 3.8? I had to move from 3.7 to 3.8 due to this issue: https://issuetracker.google.com/issues/155215191 – Jostein Sortland Aug 07 '20 at 08:57
1

Did you mean to return from get_env?

def get_env():
    print(os.environ)
    if 'GCP_PROJECT' in os.environ:
       return os.environ['GCP_PROJECT']

That can probably be simplified to just the following line:

environment = os.environ.get('GCP_PROJECT')
Dustin Ingram
  • 15,737
  • 2
  • 40
  • 56