gcloud auth print-identity-token
命令打印指定帐户的身份令牌。
$(gcloud auth print-identity-token \
--audiences=https://example.com \
--impersonate-service-account [email protected] \
--include-email)
如何使用 Python 执行相同操作?
这里是一个代码示例(不是那么简单且有详细记录)
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)
更简单。
import os
token = os.system("gcloud auth print-identity-token")