跨GCP项目创建Cloud Monitoring自定义指标遇权限问题求助
跨GCP项目创建Cloud Monitoring自定义指标解决方案
问题原因
默认情况下,MetricServiceClient会自动使用Cloud Function的默认服务账号(ServAccA)的凭据发起请求,但并未触发对ServAccB的模拟逻辑,导致请求以ServAccA的身份访问Project_B,而ServAccA本身没有Project_B的指标创建权限。
解决步骤
- 引入
google.auth相关库,创建可模拟目标服务账号的凭据 - 显式指定要模拟的ServAccB邮箱与所需权限范围,生成模拟凭据
- 用该凭据初始化
MetricServiceClient,确保请求以ServAccB身份发送
修正后的完整代码
from google.cloud import monitoring_v3 from google.auth import impersonated_credentials import google.auth # 获取Cloud Function默认服务账号的基础凭据 base_credentials, _ = google.auth.default() # 配置要模拟的目标服务账号信息(替换为实际信息) target_service_account = "servaccb@project-b.iam.gserviceaccount.com" target_scopes = [ "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/monitoring", "https://www.googleapis.com/auth/monitoring.write" ] # 创建模拟凭据 impersonated_creds = impersonated_credentials.Credentials( source_credentials=base_credentials, target_principal=target_service_account, target_scopes=target_scopes, lifetime=3600 # 凭据有效期,单位秒 ) # 使用模拟凭据初始化MetricServiceClient client = monitoring_v3.MetricServiceClient(credentials=impersonated_creds) project_name = "projects/project_B" # 替换为实际Project_B ID # 创建指标描述符(修正原代码中未定义的ga_metric引用) descriptor = monitoring_v3.MetricDescriptor() descriptor.type = "custom.googleapis.com/my_metric" descriptor.metric_kind = monitoring_v3.MetricDescriptor.MetricKind.GAUGE descriptor.value_type = monitoring_v3.MetricDescriptor.ValueType.DOUBLE descriptor.description = "This is my custom metric." # 补充标签定义逻辑(原代码仅定义列表未关联到指标) for label_key in ["id", "ip_address", "hostname"]: label = monitoring_v3.LabelDescriptor() label.key = label_key label.value_type = monitoring_v3.LabelDescriptor.ValueType.STRING label.description = f"Label for {label_key}" descriptor.labels.append(label) # 创建自定义指标 descriptor = client.create_metric_descriptor( name=project_name, metric_descriptor=descriptor) print(f"Created metric descriptor: {descriptor.name}")
额外检查项
- 确认ServAccA在ServAccB的IAM设置中被授予
roles/iam.serviceAccountTokenCreator权限,允许其模拟ServAccB - 确认ServAccB已在Project_B中绑定
roles/monitoring.metricWriter(或包含monitoring.metricDescriptors.create权限的自定义角色)
内容的提问来源于stack exchange,提问作者ds_Abc
相关产品推荐
相关产品推荐

