1. RBAC Authorization
Role-based access control (RBAC) is a method of regulating access to computer or network resources based on the roles of individual users within your organization.
更多内容,参考Using RBAC Authorization。
《为K8S创建用户账户和服务账户》一文中,我们创建了新用户jane,并且使用CA证书给该用户签发了证书。现在我们有了jane.crt和jane.key,本文中会给jane配置一些k8s集群的管理权限。
2. 角色和绑定
首先,给用户jane配置权限,使其能够创建和查看default空间下的pods。
2.1. 命令实现授权
1、创建角色
1 | kubectl create role --help |
2、角色绑定
1 | kubectl create rolebinding dev-user-binding --role=developer --user=jane |
2.2. manifest实现授权
直接通过配置清单,也可以实现角色创建和角色绑定。
1、创建授权文件auth.yaml
1 |
|
2、执行授权
1 | kubectl apply -f auth.yaml |
2.3. 验证权限
1 | kubectl auth can-i list pods --as jane |
至此,用户jane的权限配置完成。
3. 集群角色和绑定
以上,给jane授权,是在namespace范围内的。当我们想给jane授权cluster范围的权限时,就需要clusterroles。
比如,我们想给jane授权node相关的权限,可以如下实现。
3.1. 命令实现
1、创建集群角色
1 | kubectl create clusterrole node-reader --verb=get,list,watch --resource=nodes |
2、绑定集群角色
1 | kubectl create clusterrolebinding node-reader-binding --user=jane --clusterrole=node-reader |
3.2. manifest实现
1、创建授权文件auth.yaml
1 |
|
2、执行授权
1 | kubectl apply -f auth.yaml |
4. 授权范围
如果使用clusterrole指定的资源是pods这种namespace级别的资源,该集群角色绑定给jane后会有什么效果?
答:jane对所有namespace中的pods资源拥有clusterrole中定义的操作权限。
- ClusterRole + ClusterRoleBinding = All Namespaces
- ClusterRole + RoleBindings = Particular Namespaces
- Role + RoleBinding = Same Namespace
更多内容参考How to Use ClusterRoleBinding With A ServiceAccount in All Namespaces (or a few)
5. logs&exec命令权限授权
1 | apiVersion: rbac.authorization.k8s.io/v1 |
详情参考kubernetes RBAC role verbs to exec to pod
6. CRD资源授权
如果是CRD资源需要授权,可以先查看CRD资源,然后写入到yaml文件。例如,想要授权sparkapplition资源的操作权限:
1、首先查看spark crd资源
1 | kubectl get crd | grep spark |
看到内容为:
1 | scheduledsparkapplications.sparkoperator.k8s.io |
2、编写clusterrole yaml
1 | apiVersion: rbac.authorization.k8s.io/v1 |
7. 用户账户访问K8S集群
用户jane已经拥有了需要的权限,该怎样访问k8s集群呢?答案是通过kubeconfig文件。
7.1. 获取集群基本信息
假设当前用户是admin,那么可以通过命令拿到apiserver地址和ca.crt文件。
1、查看apiserver地址
1 | kubectl config view | grep server |
2、保存ca.crt
1 | cat ~/.kube/config | grep certificate-authority-data | awk '{print $2}' | base64 --decode > ca.crt |
7.2. 生成jane.kubeconfig
1、生成(设置)kubeconfig集群参数
1 | kubectl config set-cluster kubernetes \ |
当前目录生成jane.kubeconfig文件。
2、设置kubeconfig客户端认证参数
1 | kubectl config set-credentials jane \ |
3、设置kubeconfig上下文参数
1 | kubectl config set-context jane@kubernetes \ |
4、查看配置
1 | cat jane.kubeconfig |
7.3. 验证访问
1、设置默认上下文
1 | export KUBECONFIG=jane.kubeconfig |
2、测试执行命令
1 | kubectl get pods |
如果没有配置权限,会输出:
1 | Error from server (Forbidden): pods is forbidden: User "jane" cannot list resource "pods" in API group "" in the namespace "default" |
如果配置好了权限,会输出pod相关信息。
但是,以上权限测试只是在minikube或者katacoda平台生效。
如果使用kodekloud或者阿里云k8s集群,会报错:
1 | error: You must be logged in to the server (Unauthorized) |
研究了四个多小时,才发现是平台的问题,服气了。。。
8. 后记
以上,就实现了用户账户的授权方法和访问k8s的方法。
服务账户的授权方法和访问k8s的方法类似,但是略有不同,详情请参阅《好好学K8S:K8S中服务账户的RBAC鉴权》