我正在使用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'">