RBAC 的全称是Role-Based Access Control , 这套机制是Kubernetes中专门负责授权的,例如某个“用户” 可以操作哪些资源
首先我们要明确两个概念:
1, ROLE : 其实原理上是一组规则,定了了一些操作,例如,get pod , get deployment, delete pod ,但是这个地方并没有定义谁,也就是说谁和我这个Role 绑定了,谁就拥有了我这个ROLE里边定义的操作权限
2,RoleBinding: 记录了ROLE和谁绑定 了(“用户”,“组”,serviceaccount,node…)
Kubernetes 中并没有User 和 Group的 , 它在kubernetes中只是一个逻辑概念,具体的用户是用外部第三方提供的,例如github ,aws
我们看一个Role例子:
1 2 3 4 5 6 7 8 |
kind: ClusterRole apiVersion: rbac.authorization.k8s.io/v1 metadata: name: example-clusterrole rules: - apiGroups: [""] resources: ["pods"] verbs: ["get", "watch", "list"] |
这个Role的就是定义了说,谁挂载了我这个ROle 就可以对Pods 这个对象进行三个操作: get watch list
我们创建完Role之后就可以创建rolebinding了
1 2 3 4 5 6 7 8 9 10 11 12 13 |
kind: RoleBinding apiVersion: rbac.authorization.k8s.io/v1 metadata: name: example-rolebinding namespace: mynamespace subjects: - kind: User name: example-user apiGroup: rbac.authorization.k8s.io roleRef: kind: Role name: example-role apiGroup: rbac.authorization.k8s.io |
这个rolebindings的意思就是说,在mynamespace下,User : example-user 绑定了example-role 这个普通role,拥有了这个role里边所有的权限(从上边的例子我们知道这个用户能对Pods 对象进行 get watch list)
普通的role 和 rolebindings是对某个namespace 起作用的,有时候我们可能想所有的namespace都生效,肯定不可能每个namespace去创建,这个时候,kubernetes提供给我们了两个全局的概念:
ClusterRole 和 ClusterRoleBinding 用法一模一样,只不过没有了namespace :
1 2 3 4 5 6 7 8 |
kind: ClusterRole apiVersion: rbac.authorization.k8s.io/v1 metadata: name: example-clusterrole rules: - apiGroups: [""] resources: ["pods"] verbs: ["get", "watch", "list"] |
1 2 3 4 5 6 7 8 9 10 11 12 |
kind: ClusterRoleBinding apiVersion: rbac.authorization.k8s.io/v1 metadata: name: example-clusterrolebinding subjects: - kind: User name: example-user apiGroup: rbac.authorization.k8s.io roleRef: kind: ClusterRole name: example-clusterrole apiGroup: rbac.authorization.k8s.io |
这里我们说一下serviceaccount 的概念,serviceaccount相当于系统用户:
创建非常简单:
1 2 3 4 5 |
apiVersion: v1 kind: ServiceAccount metadata: namespace: mynamespace name: example-sa |
然后我们可以通过rolebinds 给这个serviceaccount 权限
1 2 3 4 5 6 7 8 9 10 11 12 13 |
kind: RoleBinding apiVersion: rbac.authorization.k8s.io/v1 metadata: name: example-rolebinding namespace: mynamespace subjects: - kind: ServiceAccount name: example-sa namespace: mynamespace roleRef: kind: Role name: example-role apiGroup: rbac.authorization.k8s.io |
当我们创建完serviceaccount以后,系统会自动创建一个secret对象,这个就是Token,也就是Serviceaccount用这个secret里边的令牌和kubernetes api进行交互
这个时候,我们创建pod的时候就可以使用serviceaccount了
1 2 3 4 5 6 7 8 9 10 |
apiVersion: v1 kind: Pod metadata: namespace: mynamespace name: sa-token-test spec: containers: - name: nginx image: nginx:1.7.9 serviceAccountName: example-sa |
启动后,我们容器里边的应用,就可以使用我们serviceaccount的token(会自动挂载进去)来和api进行交互,可以做GET、WATCH 和 LIST
默认情况下,你的Pod会自动挂载namespace下的default serviceaccount
Latest posts by Zhiming Zhang (see all)
- aws eks node 自动化扩展工具 Karpenter - 8月 10, 2022
- ReplicationController and ReplicaSet in Kubernetes - 12月 20, 2021
- public key fingerprint - 5月 27, 2021