Python equivalent for gcloud auth print-identity-token command

Question:

The gcloud auth print-identity-token command prints an identity token for the specified account.

$(gcloud auth print-identity-token 
        --audiences=https://example.com 
        --impersonate-service-account [email protected] 
        --include-email)

How do I do the same using Python?

Asked By: nipy

||

Answers:

Here a code sample (not so easy and well documented)

import google.auth.transport.requests
from google.auth.impersonated_credentials import IDTokenCredentials
SCOPES = ['https://www.googleapis.com/auth/cloud-platform']

request = google.auth.transport.requests.Request()

audience = 'my_audience'

creds, _ = google.auth.default(scopes=SCOPES)
icreds = google.auth.impersonated_credentials.Credentials(
        source_credentials=creds,
        target_principal="SA TO IMPERSONATE",
        target_scopes=SCOPES)

id = IDTokenCredentials(icreds, target_audience=audience,include_email=True)
id.refresh(request)
print(id.token)
Answered By: guillaume blaquiere