首页 > 解决方案 > googleapiclient HttpError 403 需要权限

问题描述

我正在使用 google api、googleapiclient.discovery 和 build.instances().list() 来提取我的 gcp 项目下的所有实例信息。但我有权限错误。

我可以在本地和 compute.instances().list() 上运行 compute.instances().list() 并使用应用程序默认凭据。但是,当我将应用程序发布到服务器时,默认凭据不起作用,并且会引发异常:

raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)
2019-07-17T00:55:56.682326031Z google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials.

所以我需要明确设置凭据。我将服务帐户密钥下载为“credential.json”并尝试将 GOOGLE_APPLICATION_CREDENTIALS 设置如下

import googleapiclient.discovery
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]= "credential.json"

compute = googleapiclient.discovery.build('compute', 'v1')
compute.instances().list(project="projectname", zone = "us-west1-a").execute()

但是我收到了权限错误

Traceback (most recent call last):
  File "lst_temp.py", line 6, in <module>
    compute.instances().list(project="project-name", zone = "us-west1-a").execute()
  File "/usr/local/lib/python3.7/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/googleapiclient/http.py", line 851, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/compute/v1/projects/project-name/zones/us-west1-a/instances?alt=json returned "Required 'compute.instances.list' permission for 'projects/projectname'">

标签: google-cloud-platforminstancecredentialsgoogle-api-client

解决方案


推荐阅读