nickponline
nickponline

Reputation: 25914

How do you get gcloud access token in Python?

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?

Upvotes: 4

Views: 4883

Answers (3)

marian.vladoi
marian.vladoi

Reputation: 8056

Using python:

import request
requests.get('http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token').json().get('access_token')

Upvotes: -1

Anderson Marques
Anderson Marques

Reputation: 898

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)

Upvotes: 3

Puteri
Puteri

Reputation: 3789

I think you can do this using the Google Auth Library. You can install it with pip:

$ pip install google-auth

Here's an example code using buckets:

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


KEY='/path/to/key.json'
PROJECT='your_project_id'

# gcloud auth application-default print-access-token is no necessary
credentials = service_account.Credentials.from_service_account_file(KEY)


# Initialize the Cloud Storage client using the credentials
storage_client = storage.Client(PROJECT,credentials)

# List objects in a bucket
blobs = storage_client.list_blobs("a_bucket")

for blob in blobs:
    print(blob.name)

Good luck coding!

Upvotes: 2

Related Questions