Find GCP project name

PHOTO EMBED

Tue Jan 18 2022 01:22:39 GMT+0000 (UTC)

Saved by @jmbenedetto #python

def get_gcp_project_name():
    """
    ()-->str
    Get the project_id from GOOGLE_APPLICATION_CREDENTIALS (if running locally) or metadata.google.internal (if running on GCF).

    :return bucket_name: str
    """
    # if this is running locally then GOOGLE_APPLICATION_CREDENTIALS should be defined
    if os.getenv('GOOGLE_APPLICATION_CREDENTIALS'):
        with open(os.environ['GOOGLE_APPLICATION_CREDENTIALS'], 'r') as fp:
            credentials = json.load(fp)
        gcp_project = credentials['project_id']
    # If this is running in a cloud function, then get gcp_project from url
    else:
        metadata_server = "http://metadata.google.internal/computeMetadata/v1/project/project-id"
        metadata_flavor = {'Metadata-Flavor' : 'Google'}
        gcp_project = requests.get(metadata_server, headers = metadata_flavor).text
    return gcp_project
content_copyCOPY