I am using monitoring_v3 client in Python to create a cloud monitoring custom metric in Project_B. I have written a cloud function for this and deployed it in Project_A.
So I am not passing any credentials explicitly to MetricServiceClient. But I get an error "details = "Permission monitoring.metricDescriptors.create denied (or the resource may not exist)."" when I run this cloud function. Below is my cloud function in Project_A. Need suggestions on how to make this work - Creating custom metrics in a GCP project using a cloud function in another GCP project. Thanks.
from google.cloud import monitoring_v3
client = monitoring_v3.MetricServiceClient()
project_name = "projects/project_B"
desc_labels = ["id", "ip_address", "hostname"]
descriptor = ga_metric.MetricDescriptor()
descriptor.type = "custom.googleapis.com/my_metric"
descriptor.metric_kind = ga_metric.MetricDescriptor.MetricKind.GAUGE
descriptor.value_type = ga_metric.MetricDescriptor.ValueType.DOUBLE
print(f"Value type set to: {descriptor.value_type}")
descriptor.description = "This is my custom metric."
descriptor = client.create_metric_descriptor(
name=project_name, metric_descriptor=descriptor)
It looks like you need to use the impersonated credentials explicitly. You need to use auth.impersonated_credentials
in order to obtain target credentials and use it while initializing a MetricServiceClient
.
from google.cloud import monitoring_v3
from google impott auth
# Get cloud function credentials
credentials, _ = auth.default()
# Here is you should put your target principal
target_principal = 'servaccB@project_B.iam.gserviceaccount.com'
# Create impersonated credentials
impersonated_creds = auth.impersonated_credentials.Credentials(
source_credentials=credentials,
target_principal=target_principal,
target_scopes=['https://www.googleapis.com/auth/cloud-platform'],
lifetime=3600
)
# Create the MetricServiceClient with the impersonated credentials
client = monitoring_v3.MetricServiceClient(credentials=impersonated_creds)
# ...