RBAC API 聲明瞭四種 Kubernetes 對象:Role、ClusterRole、RoleBinding 和 ClusterRoleBinding。你可以像使用其他 Kubernetes 對象一樣, 通過類似 kubectl
這類工具 描述對象, 或修補對象
clusterrole在生產中比較常用,一般用於對集羣權限的控制,比如說,對其它k8s管理員進行權限劃分, 針對不同的成員劃分不同的權限,比如說,xxx可以查看namespace權限,xxx可以查看pods或者service權限等等
1、創建一個聚合clusterrole.yaml文件,該yaml文件中“rules”是沒有任何權限配置的
#vim aggregation.yaml
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: aggregation
aggregationRule:
clusterRoleSelectors:
- matchLabels:
rbac.example.com/aggregate-to-aggregation: "true"
rules: []
#kubectl create -f aggregation.yaml
查看所創建的聚合clusterrole資源名稱
#kubectl get -f a-clusterrole.yaml.
NAME CREATED AT
aggregation 2021-05-21T03:20:39Z
2、創建一個serviceaccount服務賬號,用於綁定到secret token
#kubectl create sa aggregation
3、查看當前命名空間下的secret
# kubectl get secret
NAME TYPE DATA AGE
aggregation-token-f692k kubernetes.io/service-account-token 3 3h55m #聚合clusterrole生成的secret
default-token-gpww6 kubernetes.io/service-account-token 3 11d
4、將名爲"aggregation"的clusterrole的權限授予“default”這個命名空間下的“aggregation”用戶
#kubectl create clusterrolebinding test-aggregation --clusterrole=aggregation --serviceaccount=default:aggregation
5、創建另一個clusterrole,並保證其labels標籤與聚合clusterrole規則一致
#vim b-clusterrole.yaml
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: b-aggregation
labels:
rbac.example.com/aggregate-to-aggregation: "true"
rules:
- apiGroups: [""]
resources: ["pods","services","endpoints","namespaces"] #通過修改該權限,實現對集羣的權限控制
verbs: ["get","list","watch"]
#kubectl create -f b-clusterrole.yaml
#kubectl describe secret aggregation
複製該token,登錄到dashboards界面,可以發現所能對應的權限是聚合clusterrole所限制的
假設禁止該secretaccount訪問pods,只需要把b-aggregation.yaml的權限修改即可,如下
#vim b-clusterrole.yaml
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: b-aggregation
labels:
rbac.example.com/aggregate-to-aggregation: "true"
rules:
- apiGroups: [""]
resources: ["namespaces","services","endpoints"] #只保留查看namespaces、services、service等權限
verbs: ["get","list","watch"]
#kubectl replace -f b-clusterrole.yaml
#kubectl describe clusterrole aggregation
我們會發現,命名空間下所有的pod都沒有權限查看了