在Kubernetes中使用RBAC限制租户仅查看指定namespace指标的Role YAML
解读
国内生产级 Kubernetes 集群普遍采用多租户共享 Prometheus 的“中心采集+分权查询”模式。
面试官真正想验证的是:
- 你是否理解 Prometheus 的指标数据在 K8s 中最终通过 kube-apiserver 暴露(ServiceMonitor/PodMonitor 只是采集声明,RBAC 作用在查询阶段);
- 能否把“只看某 namespace 的指标”翻译成“只读该 namespace 下 Prometheus 相关 API 资源”的细粒度权限;
- 是否熟悉 Prometheus Operator 提供的 CRD(prometheusrules、alertmanagers、prometheuses 等)以及 metrics API 的 subresource 路径;
- 是否具备安全意识:最小权限、防止越权 list/watch、对 secrets/configmaps 的只读范围做二次裁剪。
知识点
- Prometheus Operator 架构:Prometheus CR → StatefulSet → Prometheus Server;外部查询统一走 kube-apiserver 的 /api/v1/namespaces/{ns}/services/{svc}/proxy/ 路径。
- RBAC 四要素:Role/ClusterRole、RoleBinding/ClusterRoleBinding、Resource、Verb。
- 指标查询权限实际落在 “services/proxy” 子资源;Prometheus HTTP API 路径 /api/v1/query 等对应 subresource 的 get 动词。
- 只暴露 namespace 级别资源:禁止 list/watch 集群级 CRD(如 ClusterRole、NodeMetrics),防止通过标签反推全局拓扑。
- 国内金融/运营商合规要求:敏感标签(pod 名称、镜像 tag)不得透出,需配合 Prometheus 的 metric_relabel_config 在采集侧丢弃;RBAC 侧只解决“能看/不能看”。
答案
以下 Role 直接绑定到租户使用的 ServiceAccount,限制其仅能在 namespace “app-team-a” 内做指标查询与基础资源只读,满足国内主流合规基线。
保存为 prometheus-viewer-role.yaml:
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: prometheus-namespace-reader
namespace: app-team-a # 目标租户 NS
rules:
# 1. 核心:只读 Prometheus HTTP API(/api/v1/query*)
- apiGroups: [""]
resources: ["services/proxy"]
resourceNames: ["prometheus-operated"] # Operator 默认 svc
verbs: ["get"]
# 2. 只读本 NS 内的 ServiceMonitor/PodMonitor/Rules
- apiGroups: ["monitoring.coreos.com"]
resources:
- servicemonitors
- podmonitors
- prometheusrules
verbs: ["get", "list", "watch"]
# 3. 只读本 NS 内的 CM/Secret(Grafana 面板、告警模板)
- apiGroups: [""]
resources: ["configmaps", "secrets"]
verbs: ["get", "list"]
resourceNames: ["grafana-dashboard-app-team-a", "alert-template-app-team-a"]
# 4. 只读本 NS 内的 Deploy/STS/Pod(排障需要)
- apiGroups: ["apps"]
resources: ["deployments", "statefulsets"]
verbs: ["get", "list", "watch"]
- apiGroups: [""]
resources: ["pods", "pods/log"]
verbs: ["get", "list", "watch"]
对应 RoleBinding:
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: prometheus-namespace-reader-binding
namespace: app-team-a
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: prometheus-namespace-reader
subjects:
- kind: ServiceAccount
name: app-team-a-sa
namespace: app-team-a
验证命令(租户视角):
kubectl auth can-i get services/proxy --subresource=prometheus-operated -n app-team-a
# 输出: yes
kubectl auth can-i list nodes
# 输出: no
拓展思考
- 若集群使用 VictoriaMetrics Operator 或 Thanos Query Frontend,proxy 路径会变,需要同步调整 resourceNames 与 apiGroup。
- 国内等保 2.0 要求审计:开启 kube-apiserver 的 audit-policy,把 “services/proxy” get 请求按 namespace 打标签,接入 ELK/ Loki 做留存。
- 当租户需要临时跨 NS 聚合指标(如链路追踪全局拓扑),可引入“只读聚合账号”+“临时 TokenRequest(TTL≤1h)” 的方案,避免永久 ClusterRole。
- 大规模场景(>5k 节点)建议把 Prometheus 拆成“分片采集+统一查询”两层:RBAC 只在查询层做限制,采集层使用专用高权 SA,防止规则越权导致内存爆炸。