Search code examples
pythongoogle-cloud-platformgoogle-cloud-sqlstackdrivergoogle-cloud-stackdriver

Error while fetching GCP monitoring via GCP Python API


I'm trying to fetch last 5 mins CPU utilization of a GCP SQL instance but getting following error. Please help me resolve it. The service account I'm using has full read permission over monitoring.

My script:

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())

Error:

  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).

Solution

  • Removing the prefix "projects/" worked. So basically using project id instead of project_name worked.

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