¿Cómo iniciar sesión en Google Cloud Storage desde una función de Python?

Aug 24 2020

Soy nuevo en el almacenamiento en la nube de Google e intento configurar una función que descargue un blob una vez al día. En este momento estoy trabajando en mi Jupyter Notebook pero finalmente, el código se ejecutará en una función de Azure. Estoy luchando por configurar el cliente que me conecta con el cubo. Tengo una credencial de cuenta de servicio JSON que me permite conectarme a Google.

Localmente he encontrado una solución:

from google.cloud import storage

client = storage.Client.from_service_account_json('<PATH_TO_SERVICE_ACCOUNT_JSON>')

El problema es que no tengo una ruta donde almaceno mi JSON en la nube pero lo guardo en la bóveda de claves. Se me ocurrió la siguiente solución:

from google.cloud import storage
import json
from google.oauth2 import service_account

string_key = get_key_from_key_vault()
service_account_info = json.loads(string_key)
google_credentials = service_account.Credentials.from_service_account_info(
    service_account_info
)
scoped_credentials = google_credentials.with_scopes(
    ['https://www.googleapis.com/auth/cloud-platform.read-only'])
print(type(scoped_credentials))
client = storage.Client(credentials = scoped_credentials)

No estoy totalmente seguro de si necesito la scoped_credentials = ...pieza, pero solo tengo permisos de lectura en el depósito. (si me salto la parte, el error sigue siendo el mismo)

Cuando busco esta solución, aparece el siguiente error:

DefaultCredentialsError: Could not automatically determine credentials. Please set 
GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For
 more information, please see https://cloud.google.com/docs/authentication/getting-started

No tengo ni idea de lo que estoy haciendo mal porque creo que ya configuré las credenciales explícitamente.

Mejor P

Respuestas

1 JanHernandez Aug 24 2020 at 20:44

you can set the environment variable GOOGLE_APPLICATION_CREDENTIALS with the path of the json file and authenticate your function by starting the storage client without parameters.

client = storage.Client()

*by default the storage client uses the file path on the environment variable GOOGLE_APPLICATION_CREDENTIALS

It is the easiest way to use JSON credentials and it is compatible with most of Google Cloud python libraries.

1 Pet Aug 25 2020 at 08:41

after some more tests i found out that I missed to add project = None. If you add it an use the following command to create the client it works:

client = storage.Client(project = None, credentials = scoped_credentials)

Thanks for your help and food for thought :-)

guillaumeblaquiere Aug 24 2020 at 19:19

(I use the answer part because code formatting in comment is awful)

Can you try this and tell me if you see the 2 access token printed?

from google.cloud import storage
import json
from google.oauth2 import service_account
from google.auth.transport import requests as grequests

string_key = get_key_from_key_vault()
service_account_info = json.loads(string_key)

google_credentials = service_account.Credentials.from_service_account_info(
    service_account_info
)
google_credentials.refresh(grequests.Request())
print(google_credentials.token)


scoped_credentials = google_credentials.with_scopes(
    ['https://www.googleapis.com/auth/cloud-platform.read-only'])
scoped_credentials.refresh(grequests.Request())
print(scoped_credentials.token)