You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用服务账号与JWT认证调用Google Cloud Monitoring API遇403权限错误

解决Google Cloud Monitoring服务账号403 Permission monitoring.timeSeries.list denied问题

问题背景

我在本地环境运行以下Python代码调用Google Cloud Monitoring API查询L4负载均衡的新连接数,使用服务账号认证时始终返回403权限错误,但改用gcloud CLI配置的用户账号认证就能正常运行。

运行代码

from google.oauth2 import service_account
from google.cloud import monitoring_v3

def build_time(isodate: str) -> int:
    from datetime import datetime
    
    utc_dt = datetime.strptime(isodate, '%Y-%m-%dT%H:%M:%S.%fZ')
    return int((utc_dt - datetime(1970, 1, 1)).total_seconds())

SCOPES = [
    "https://www.googleapis.com/auth/cloud-platform",
    "https://www.googleapis.com/auth/monitoring",
    "https://www.googleapis.com/auth/monitoring.read"
]
SERVICE_ACCOUNT_FILE = '/path/to/service_account_file.json'

credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)

client = monitoring_v3.MetricServiceClient(credentials=credentials)

name = 'projects/MY_PROJECT_NAME'
filter = 'metric.type = "loadbalancing.googleapis.com/l4_proxy/tcp/new_connections_count"'
end_time = build_time('2024-10-22T10:40:00.000Z')
start_time = build_time('2024-10-22T10:30:00.000Z')
interval = monitoring_v3.TimeInterval({
    "end_time": {"seconds": end_time},
    "start_time": {"seconds": start_time},
})
request = monitoring_v3.ListTimeSeriesRequest(
        name=name,
        filter=filter,
        interval=interval
    )

try:
    page_result = client.list_time_series(request=request)    
except Exception as error:
    print("Error happened:", error)
    exit()

print(page_result)

依赖版本

google-auth==2.35.0
google-cloud-monitoring==2.23.0

错误信息

Error happened: 403 Permission monitoring.timeSeries.list denied (or the resource may not exist).

解决方案

  • 确认服务账号绑定正确IAM角色
    必须给服务账号分配至少Monitoring Viewer(roles/monitoring.viewer)角色,该角色包含monitoring.timeSeries.list权限。在GCP控制台IAM页面找到对应服务账号,检查已分配角色,确保包含该角色。角色变更需等待几分钟生效后再测试。

  • 验证服务账号密钥有效性
    确保代码中SERVICE_ACCOUNT_FILE路径正确,密钥文件是从GCP控制台下载的最新有效文件,未过期或被撤销。可通过以下命令行验证:

    gcloud auth activate-service-account --key-file=/path/to/service_account_file.json
    gcloud monitoring time-series list --filter='metric.type="loadbalancing.googleapis.com/l4_proxy/tcp/new_connections_count"' --start-time=2024-10-22T10:30:00Z --end-time=2024-10-22T10:40:00Z --project=MY_PROJECT_NAME
    

    若该命令也报错,说明是服务账号本身权限问题,而非代码问题。

  • 检查项目名称正确性
    确认代码中name = 'projects/MY_PROJECT_NAME'里的MY_PROJECT_NAME是实际GCP项目ID(不是显示名称),项目ID为唯一小写字符串,包含字母、数字和横线。

  • 简化权限范围
    cloud-platform范围已覆盖Monitoring相关权限,可简化Scopes配置:

    SCOPES = ["https://www.googleapis.com/auth/cloud-platform"]
    
  • 确认Monitoring API已启用
    在GCP控制台API库中搜索"Cloud Monitoring API",确保其状态为启用。

内容的提问来源于stack exchange,提问作者ASLLOP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 18:32:04