Kubernetes中为命名空间默认ServiceAccount授权读取集群所有Ingress资源的疑问及配置排查
问题解答
核心问题:是否必须使用ClusterRole?
没错!如果你的目标是让my-namespace下的default ServiceAccount能够读取集群内所有命名空间的Ingress资源,必须使用ClusterRole搭配ClusterRoleBinding。原因很明确:
Role是命名空间级资源,它只能授予对当前命名空间内资源的访问权限;ClusterRole是集群级资源,可以用来授予跨所有命名空间的资源权限,或者访问集群级别的资源(比如节点、PersistentVolumes等)。
你当前配置的问题
你现在用的Role+RoleBinding,哪怕配置正确,也只能让ServiceAccount访问my-namespace下的Ingress。而且你的Role里的apiGroups配置存在冗余和不准确的地方:
- Ingress资源不属于核心API组(
""),也不存在networking这个API组; - 目前主流Kubernetes版本(1.19+)中,Ingress的官方API组是
networking.k8s.io,旧版本的extensions组已经被废弃。
这也是你执行kubectl auth can-i命令返回no的关键原因之一。
满足跨所有命名空间需求的正确配置
下面是实现读取集群所有Ingress资源的ClusterRole和ClusterRoleBinding清单:
apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: cluster-ingress-reader rules: - apiGroups: ["networking.k8s.io"] resources: ["ingresses"] # 注意这里是复数形式"ingresses",不是"ingress" verbs: ["get", "watch", "list"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: bind-default-sa-to-cluster-ingress-reader subjects: - kind: ServiceAccount name: default namespace: my-namespace roleRef: kind: ClusterRole name: cluster-ingress-reader apiGroup: rbac.authorization.k8s.io
验证权限
应用配置后,你可以用以下命令验证跨命名空间的权限:
# 验证能读取所有命名空间的Ingress kubectl auth can-i list ingresses --all-namespaces --as=system:serviceaccount:my-namespace:default
如果只是想让ServiceAccount访问my-namespace下的Ingress,修正后的Role+RoleBinding应该是这样:
apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: namespace: my-namespace name: namespace-ingress-reader rules: - apiGroups: ["networking.k8s.io"] resources: ["ingresses"] verbs: ["get", "watch", "list"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: bind-default-sa-to-namespace-ingress-reader namespace: my-namespace subjects: - kind: ServiceAccount name: default namespace: my-namespace roleRef: kind: Role name: namespace-ingress-reader apiGroup: rbac.authorization.k8s.io
此时再执行你原来的命令就会返回yes了:
kubectl auth can-i list ingress -n my-namespace --as=system:serviceaccount:my-namespace:default
内容的提问来源于stack exchange,提问作者noxora
相关产品推荐
相关产品推荐

