通过 GCP Python API 获取 GCP 监控时出错

Error while fetching GCP monitoring via GCP Python API

我正在尝试获取 GCP SQL 实例的最后 5 分钟 CPU 利用率,但出现以下错误。请帮我解决。我正在使用的服务帐户对监控具有完全读取权限。

我的脚本:

from google.cloud import monitoring_v3
from google.cloud.monitoring_v3 import query

credential_file = "/home/user/my-first-project.json"

GCP_SCOPES = [
    'https://www.googleapis.com/auth/sqlservice.admin',
    "https://www.googleapis.com/auth/logging.read",
    "https://www.googleapis.com/auth/cloud-platform",
    "https://www.googleapis.com/auth/monitoring",
    "https://www.googleapis.com/auth/monitoring.read"
]

gcp_credential = service_account.Credentials.from_service_account_file(credential_file,scopes=GCP_SCOPES)

client = monitoring_v3.MetricServiceClient(credentials=gcp_credential)

project_name = f"projects/my-first-project"

cpu_query = query.Query(client,
                        project=project_name,
                        metric_type='cloudsql.googleapis.com/database/cpu/utilization',
                        minutes=5)

next(cpu_query.iter())

错误:

  File "$PATH\grpc_helpers.py", line 75, in error_remapped_callable
    six.raise_from(exceptions.from_grpc_error(exc), exc)
  File "<string>", line 3, in raise_from
google.api_core.exceptions.PermissionDenied: 403 Permission monitoring.timeSeries.list denied (or the resource may not exist).

删除前缀“projects/”有效。所以基本上使用项目 ID 而不是 project_name 工作。

cpu_query = query.Query(
    client,
    project="my-first-project",                    
    metric_type='cloudsql.googleapis.com/database/cpu/utilization',
    minutes=5
)