Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save anderson-marques/51e276063df334bc6a11fa069f2495df to your computer and use it in GitHub Desktop.

Select an option

Save anderson-marques/51e276063df334bc6a11fa069f2495df to your computer and use it in GitHub Desktop.
gcloud_service_account_print_access_token
# Python script to programmatically generate the access token from a service-account key
# It does what the following commands does:
# - gcloud auth activate-service-account
# - gcloud auth print-access-token
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment