K8s-控制细粒度地创建ServiceAccount

44 阅读1分钟

创建一个 ServiceAccount,之前都是简单的deployment相关资源,现在新增了额外很多资源,所以采用 apiGroups:"*" 的方式将不推荐,本文记录如何书写细致控制RBAC

确定资源组与资源

使用命令 kubectl api-versions 可以查看到当前集群具有的 apiGroups ,特殊的是 apiGroups:[""] , "" 标明 core API 组,即 v1,详见kubernetes.io/zh-cn/docs/…) 。其他如 app/v1 则指明 apiGroups 为 app。参考链接:blog.csdn.net/random_w/ar…

可以根据 kubectl api-resources确认到每一个 Group 下有什么具体资源。

kubectl api-resources -owide可以确认到每个具体资源的 Verb动作支持哪些。

pod/logs pod/exec是属于子资源,暂时没有明确的命令查看,有相关插件通过采用 proxy+curl 的返回查看,相关链接 github.com/schollii/my… stackoverflow.com/questions/5…

创建对应配置清单

Role

apiVersion: v1
kind: ServiceAccount
metadata:
  name: user-xiaoming
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: role-user-xiaoming
rules:
- apiGroups: [""]
  resources: ["pods","secrets","services","persistentvolumeclaims","persistentvolumeclaims","namespaces","configmaps"]
  verbs: ["get","list","watch","create","update","patch","delete"]
- apiGroups: ["apps"]
  resources: ["deployments","statefulsets"]
  verbs: ["get","list","watch","create","update","patch","delete"]  
- apiGroups: ["networking.istio.io"]
  resources: ["virtualservices"]
  verbs: ["get","list","watch","create","update","patch","delete"]  
- apiGroups: ["gateway.networking.k8s.io"]
  resources: ["gatewayclasses","gateways","httproutes",]
  verbs: ["get","list","watch","create","update","patch","delete"]  
- apiGroups: [""]
  resources: ["pods/exec","pods/log","pods/describe"]
  verbs: ["get", "list", "watch", "create", "update", "patch","delete"]
- apiGroups: ["*"]
  resources: ["events"]
  verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: rolebinding-user-xiaoming
subjects:
- kind: ServiceAccount
  name: user-xiaoming
roleRef:
  kind: Role    
  name: role-user-xiaoming
  apiGroup: rbac.authorization.k8s.io

而后执行 kubectl apply -n your_namespaces -f thisyaml

检查权限

k8s 提供 auth 命令测试角色的权限,如下:

kubectl auth can-i create deployment --as=system:serviceaccount:your_namespaces:user-xiaoming

简单脚本

cat sa-test.sh

a=( deployments statefulsets services virtualservices secrets persistentvolumeclaims persistentvolumeclaims namespaces configmaps gatewayclasses gateways httproute pod/logs pods/exec pods/describe )
for i in ${a[*]}
do
        echo $i
        kubectl auth can-i create $i  --as=system:serviceaccount:your_namespaces:user-xiaoming
done

bash sa-test.sh

输出如下: