gcloud auth print-identity-token 命令的 Python 等效项

问题描述 投票:0回答:2

gcloud auth print-identity-token
命令打印指定帐户的身份令牌。

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

如何使用 Python 执行相同操作?

python google-cloud-platform gcloud
2个回答
11
投票

这里是一个代码示例(不是那么简单且有详细记录)

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)

0
投票

更简单。

import os
token = os.system("gcloud auth print-identity-token")
© www.soinside.com 2019 - 2024. All rights reserved.