Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get gcloud access token in Python?

Tags:

python

gcloud

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?

like image 238
nickponline Avatar asked Oct 20 '25 03:10

nickponline


1 Answers

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)
like image 152
Anderson Marques Avatar answered Oct 24 '25 19:10

Anderson Marques



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!