### K8S RBAC 理解
在K8S中,RBAC主要由四个核心组件组成:Role、RoleBinding、ClusterRole、ClusterRoleBinding。下面我们将详细介绍每个组件的作用,并给出相应的代码示例。
#### 1. Role
Role是一种将一组特定权限授予特定资源的对象。可以用于限制用户对当前命名空间的操作权限。
```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: default
name: pod-reader
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "watch", "list"]
```
在上面的示例中,我们创建了一个名为pod-reader的Role,赋予了对pods资源的get、watch、list权限。
#### 2. RoleBinding
RoleBinding用于将Role绑定到用户或者服务账户上。
```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: read-pods
namespace: default
roleRef:
kind: Role
name: pod-reader
apiGroup: rbac.authorization.k8s.io
subjects:
- kind: User
name: alice
apiGroup: rbac.authorization.k8s.io
```
在上面的示例中,我们将Role pod-reader绑定到用户alice上,使其具有对pods资源的get、watch、list权限。
#### 3. ClusterRole
ClusterRole类似于Role,但ClusterRole作用于整个集群,而不是单个命名空间。
```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: pod-reader
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "watch", "list"]
```
在上面的示例中,我们创建了一个名为pod-reader的ClusterRole,赋予了对整个集群中pods资源的get、watch、list权限。
#### 4. ClusterRoleBinding
ClusterRoleBinding用于将ClusterRole绑定到用户或者服务账户上。
```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: read-pods
roleRef:
kind: ClusterRole
name: pod-reader
apiGroup: rbac.authorization.k8s.io
subjects:
- kind: User
name: alice
apiGroup: rbac.authorization.k8s.io
```
在上面的示例中,我们将ClusterRole pod-reader绑定到用户alice上,使其具有整个集群中pods资源的get、watch、list权限。
### 总结
通过以上的介绍,我们可以看到K8S RBAC的基本概念及相关组件的作用和使用方法。借助RBAC,我们可以精确地控制用户或者服务账户对K8S中资源的访问权限,保障系统的安全性。
希望通过这篇文章,你已经对K8S RBAC有了更深的理解。如有任何问题,欢迎留言讨论。祝你在K8S的学习和使用过程中取得成功!