I'm looking to do the equivalent of the following in Python with out having to call these command using something like os.system and look at the output.
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/credentials.json"
export PROJECT_ID="my-project-name"
gcloud auth application-default print-access-token
Can this be done with Google SDK?
Here the answer:
import google.auth
import google.auth.transport.requests
from google.oauth2 import service_account
from os.path import expanduser
from os import getenv
# The the service account key ABSOLUTE path from env or current folder
service_account_key = getenv(
'GOOGLE_APPLICATION_CREDENTIALS',
f'{expanduser(".")}/service-account-key.json'
)
# Creates a credentials object from the service account file
credentials = service_account.Credentials.from_service_account_file(
service_account_key, # key path
scopes=['https://www.googleapis.com/auth/cloud-platform'] # scopes
)
# Prepare an authentication request
auth_req = google.auth.transport.requests.Request()
# Request refresh tokens
credentials.refresh(auth_req)
# now we can print the access token
print(credentials.token)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With