问题
我有一个简单的 RBAC 配置来访问集群内的 Kubernetes API。然而,我从 kubectl 得到的信息似乎是相互冲突的。部署 list 后,RBAC 似乎已正确设置。
$ kubectl exec -ti pod/controller -- kubectl auth can-i get namespaces
Warning: resource 'namespaces' is not namespace scoped
yes
但是,实际发出请求会产生权限错误
$ kubectl exec -ti pod/controller -- kubectl get namespaces
Error from server (Forbidden): namespaces is forbidden: User "system:serviceaccount:default:controller" cannot list resource "namespaces" in API group "" at the cluster scope
command terminated with exit code 1
list
apiVersion: 'v1'
kind: 'ServiceAccount'
metadata:
name: 'controller'
---
apiVersion: 'rbac.authorization.k8s.io/v1'
kind: 'Role'
metadata:
name: 'read-namespaces'
rules:
- apiGroups:
- ''
resources:
- 'namespaces'
verbs:
- 'get'
- 'watch'
- 'list'
---
apiVersion: 'rbac.authorization.k8s.io/v1'
kind: 'RoleBinding'
metadata:
name: 'read-namespaces'
roleRef:
apiGroup: ''
kind: 'Role'
name: 'read-namespaces'
subjects:
- kind: 'ServiceAccount'
name: 'controller'
---
apiVersion: 'v1'
kind: 'Pod'
metadata:
name: 'controller'
labels:
'app': 'controller'
spec:
containers:
- name: 'kubectl'
image: 'bitnami/kubectl:latest'
imagePullPolicy: 'Always'
command:
- 'sleep'
- '3600'
serviceAccountName: 'controller'
---
其他信息
我尝试过 kubectl auth reconcile -f manifest.yaml
以及 kubectl apply -f manifest.yaml
,结果是相同的。
我还将“read-namespaces”RoleBinding.subjects[0].namespace
设置为正确的命名空间(在本例中为“默认”)。输出没有变化。
最佳答案
命名空间是集群范围的资源。因此,您需要一个 ClusterRole
和一个 ClusterRoleBinding
。
apiVersion: 'rbac.authorization.k8s.io/v1'
kind: 'ClusterRole'
metadata:
name: 'read-namespaces'
rules:
- apiGroups:
- ''
resources:
- 'namespaces'
verbs:
- 'get'
- 'watch'
- 'list'
---
apiVersion: 'rbac.authorization.k8s.io/v1'
kind: 'ClusterRoleBinding'
metadata:
name: 'read-namespaces'
roleRef:
apiGroup: 'rbac.authorization.k8s.io'
kind: 'ClusterRole'
name: 'read-namespaces'
subjects:
- kind: 'ServiceAccount'
name: 'controller'
---
关于kubernetes - 如何设置 kubernetes RBAC 资源以便 pod 可以通过客户端访问 API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61958879/