为了从我的项目中检索监控指标,我使用了以下Python代码:
from google.cloud import monitoring_v3
from google.oauth2 import service_account
from googleapiclient import discovery
credentials = service_account.Credentials.from_service_account_file(
r'D:GCPcredentialsblahblah-04e8fd0245b8.json')
service = discovery.build('compute', 'v1', credentials=credentials)
client = monitoring_v3.MetricServiceClient()
project_name = f"projects/{blahblah-300807}"
resource_descriptors = client.list_monitored_resource_descriptors(
name=project_name)
for descriptor in resource_descriptors:
print(descriptor.type)
我把每件事都做得很好。我正确地提供了凭据信息的文件路径,但我收到了以下错误消息:
raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)
google.auth.exceptions.DefaultCredentialsError:
Could not automatically determine credentials.
Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create
credentials and re-run the application.
For more information, please see
https://cloud.google.com/docs/authentication/getting-started
我甚至检查了那个链接,并尝试了另一种方法,但仍然不起作用。我该如何纠正?我是不是搞错了?
创建客户端时不使用凭据
client = monitoring_v3.MetricServiceClient()
你可以像这个一样改变它
client = monitoring_v3.MetricServiceClient(credentials=credentials)
就我个人而言,我更喜欢不在代码中显式提供凭据,并且我更喜欢使用环境变量GOOGLE_APPLICATION_CREDENTIALS
。
在操作系统中创建一个环境变量,名称为GOOGLE_APPLICATION_CREDENTIALS
,值指向服务帐户密钥文件D:GCPcredentialsblahblah-04e8fd0245b8.json
。
但是,如果它在您自己的计算机上,您甚至可以不使用服务帐户密钥文件(这不是真正安全的,我在本文中解释了原因(,您可以使用自己的凭据。为此,只需创建一个应用程序默认凭据(ADC(,如gcloud auth application-default login