Flair
Flair

Reputation: 2907

Is there a way for Google Cloud Python Authentication via the JSON keyfile itself and not the file path?

So for Ruby, you can set the JSON content into the environmental variable of GOOGLE_CLOUD_KEYFILE_JSON. I am trying to find the documentation for Python, but all I can see is documentation loading the authentication for file path.

Upvotes: 3

Views: 3717

Answers (3)

Daniel Adelantado
Daniel Adelantado

Reputation: 38

You should be able to read the environment variables on Python using the following:

import os
print os.environ['GOOGLE_CLOUD_KEYFILE_JSON']

Upvotes: 0

Flair
Flair

Reputation: 2907

I found a way to do it, but I want to know if there is a better way. Using the google-auth library, I can do something like this:

import json

from google.cloud import bigquery
from google.oauth2 import service_account

"""
Securely get content of JSON file from protected memory because having
the credential file plainly on the filesystem is unsafe
"""

service_account_info = json.loads(json_file_content_string)
credentials = service_account.Credentials.from_service_account_info(service_account_info)
client = bigquery.Client(project='secret-proj', credentials=credentials)

More about the library here: https://google-auth.readthedocs.io/en/latest/reference/google.oauth2.service_account.html

Upvotes: 8

Dustin Ingram
Dustin Ingram

Reputation: 21550

Nope, you need to set GOOGLE_APPLICATION_CREDENTIALS with a path to the JSON file instead.

See https://cloud.google.com/docs/authentication/getting-started for more details.

Upvotes: -1

Related Questions