python - 在 Cloud Functions 中获取服务帐户凭据以在 GCP 之外调用 google 服务
问题描述
我的场景:我需要google-api-python-client
使用服务帐户从 Cloud Function 调用 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 错误。
使用Cloud Function 中设置keyfile.json
的相同服务帐户。[service-account]@[project].iam.gserviceaccount.com
解决方案
您必须强制库生成令牌以强制它完成所有字段。为此,只需调用一次重试,就像这样
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)
推荐阅读
- javascript - 从功能组件发送功能道具时防止重新渲染
- pdf - pdf中的Birt导出不会自动换行长行
- c# - 如何在 c# 的 azure 管道中运行 Selenium UI 测试。OpenQA.Selenium.WebDriverException :对远程 WebDriver 服务器的 HTTP 请求以获取 URL
- security - 为什么 aqua microscanner 在我的 Jenkinsfile 中失败?
- bash - 从包含“\n”的变量中插入字符串而不用换行文字替换
- python - 最快的 DataFrame 或 Dictionary
- scala - 无法在 Spark(Scala)中的数据帧上执行用户定义的函数
- c++ - int main() 是否需要在 C++ 上声明?
- android - 当我尝试实例化 ViewModelProviders 时,无法解析 of() 方法
- django - 如何通过 Queryset 在 Python 函数中访问 Django 模型实例的“absolute_url”