创建Cloud Functions告警时google.protobuf.Duration类型错误如何解决?
问题根因
你遇到的报错核心有两点:
- 原写法中直接在JSON结构里写
900s属于非法JSON格式,本身就会触发语法错误 - Google Cloud Monitoring API要求告警策略中的
duration参数必须为google.protobuf.Duration类型实例,直接传入整数、普通字符串均无法通过类型校验
正确实现方式(以Cloud Functions最常用的Python运行环境为例)
- 首先导入protobuf的Duration类
from google.protobuf.duration_pb2 import Duration
- 实例化Duration对象,设置对应时长
# 配置为你需要的900秒 alert_duration = Duration() alert_duration.seconds = 900
- 将实例填入告警策略的对应字段即可
alert_policy = { "conditions": [ { "condition_absent": { "duration": alert_duration, "filter": 'metric.label.state="blocked" AND metric.type="agent.googleapis.com/processes/count_by_state" AND resource.type="gce_instance"' }, "displayName": "Test_two" } ], "displayName": "test", "combiner": "OR" }
其他场景适配
- 若使用Node.js、Go等其他语言的GCP官方客户端,直接传入符合结构的对象即可,示例:
{ seconds: 900, nanos: 0 } - 若直接调用REST API而非使用官方客户端,可传入带
s后缀的字符串格式:"duration": "900s"
内容的提问来源于stack exchange,提问作者Simon Breton
相关产品推荐
相关产品推荐

