我已经创建了一个服务帐户,并提供了JSON格式的私钥(/adc.json
)。它可以通过Client.from_service_account_json
函数加载到google-cloud python客户端。但是,当我尝试调用Monitoring API来编写自定义指标时,它会收到403错误,如下所示。
In [1]: from google.cloud import monitoring
In [2]: c = monitoring.Client.from_service_account_json('/adc.json')
In [6]: resource = client.resource('gce_instance', labels={'instance_id': '1234567890123456789', 'zone': 'us-central1-f'})
In [7]: metric = client.metric(type_='custom.googleapis.com/my_metric', labels={'status': 'successful'})
In [9]: from datetime import datetime
In [10]: end_time = datetime.utcnow()
In [11]: client.write_point(metric=metric, resource=resource, value=3.14, end_time=end_time)
---------------------------------------------------------------------------
Forbidden Traceback (most recent call last)
<ipython-input-11-b030f6399aa2> in <module>()
----> 1 client.write_point(metric=metric, resource=resource, value=3.14, end_time=end_time)
/usr/local/lib/python3.5/site-packages/google/cloud/monitoring/client.py in write_point(self, metric, resource, value, end_time, start_time)
599 timeseries = self.time_series(
600 metric, resource, value, end_time, start_time)
--> 601 self.write_time_series([timeseries])
/usr/local/lib/python3.5/site-packages/google/cloud/monitoring/client.py in write_time_series(self, timeseries_list)
544 for timeseries in timeseries_list]
545 self._connection.api_request(method='POST', path=path,
--> 546 data={'timeSeries': timeseries_dict})
547
548 def write_point(self, metric, resource, value,
/usr/local/lib/python3.5/site-packages/google/cloud/_http.py in api_request(self, method, path, query_params, data, content_type, headers, api_base_url, api_version, expect_json, _target_object)
301 if not 200 <= response.status < 300:
302 raise make_exception(response, content,
--> 303 error_info=method + ' ' + url)
304
305 string_or_bytes = (six.binary_type, six.text_type)
Forbidden: 403 User is not authorized to access the project monitoring records. (POST https://monitoring.googleapis.com/v3/projects/MY-PROJECT/timeSeries/)
在GCP的访问控制面板中,我没有看到Stackdriver Monitoring API的特定预定义角色范围。请参见下面的截图:
我已尝试Project Viewer
,Service Account Actor
预定义角色,但均未奏效。我对此服务帐户分配Project Editor
角色犹豫不决,因为感觉它对于Stackdriver专用服务帐户凭据的范围来说太宽泛了。那么分配给这个服务帐户的正确角色应该是什么?感谢。
答案 0 :(得分:3)
你是对的,它太宽泛了,我们正在研究更细粒度的角色,但是,截至今天,&#34;项目编辑&#34;是正确的角色。
如果您在GCE VM上运行并省略私钥,则默认情况下Stackdriver监视代理程序将尝试使用VM的默认服务帐户。只要VM具有https://www.googleapis.com/auth/monitoring.write
范围(默认情况下,这些天应该为所有GCE VM启用),这将起作用。有关代理所需凭据的详细说明,请参阅this page。