RBAC鉴权-通过聚合clusterrole实现集群权限控制
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都没有权限查看了