Return active GCP project name programatically for both local dev and deployed Cloud Run projects

Question:

I am working on code that will leverage GCP’s CI/CD build > deploy. Part of that process is staging it as a test deploy and running integration tests in a non-production project. That code will ultimately be promoted to a production project.

As a result, I would like to be able to dynamically adjust which project the deployed code is running under.

Is there a way to get the current environment’s active project name in python like you can with gccloud config get-value project?

I would like to work in my local development environment and in deployments on Cloud Run.

Most of the answers I’ve found are only for deployments, and because of that I can’t test locally.

This code kind of works, but I would prefer to use the GCP SDK and not resort to executing a subprocess.

try:
    project_id = os.system('gcloud %s %s %s' %("config", "get-value", "project")).read()
    print(project_id)
    pass
except:
    print("Error running command")
    pass
Asked By: Dshiz

||

Answers:

The CLI configuration information is stored in a file. The format is INI. For Python use the configparser package.

Windows:

C:Users%USERNAME%AppDataRoaminggcloudconfigurationsconfig_default

Linux:

~/.config/gcloud/configurations/config_default
Answered By: John Hanley
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.