在Cloud Functions中获取服务帐户凭据,以在GCP之外调用Google服务

时间:2020-06-30 20:56:14

标签: python google-cloud-platform google-cloud-functions google-api-python-client

我的情况:我需要使用服务帐户从Cloud Function中使用google-api-python-client调用Google DBM API。

更新

这是我尝试运行的示例代码:

import google.auth
from googleapiclient.discovery import build
from google.auth.transport import requests

API_NAME = 'doubleclickbidmanager'
API_VERSION = 'v1.1'
SCOPES = ['https://www.googleapis.com/auth/doubleclickbidmanager']

credentials, project_id = google.auth.default(scopes=SCOPES)

print(credentials.service_account_email)
# prints "default"

credentials.refresh(requests.Request())
print(credentials.service_account_email)
# prints "[service-account]@[project].iam.gserviceaccount.com"

service = build(API_NAME, API_VERSION, credentials=credentials)
service.queries().listqueries().execute()
# local: return the queries
# in CF: Encountered 403 Forbidden with reason "insufficientPermissions"

在本地运行时,设置环境变量GOOGLE_APPLICATION_CREDENTIALS=keyfile.json可以正常工作。

但是在Cloud Function中运行时,出现了403错误。

keyfile.json使用在Cloud Function中设置的相同服务帐户[service-account]@[project].iam.gserviceaccount.com

1 个答案:

答案 0 :(得分:2)

您必须强制库生成令牌以强制它满足其所有字段。为此,只需像这样调用重试

import google.auth
credentials, project_id = google.auth.default(scopes=SCOPES)

from google.auth.transport import requests
credentials.refresh(requests.Request())
print(credentials._service_account_email)

build(API_NAME, API_VERSION, credentials=credentials)