Created
March 12, 2021 20:13
-
-
Save anderson-marques/51e276063df334bc6a11fa069f2495df to your computer and use it in GitHub Desktop.
gcloud_service_account_print_access_token
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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