官方文档

1.创建sa

1
2
3
4
5
apiVersion: v1
kind: ServiceAccount
metadata:
  name: user-test   #创建的sa
  namespace: test-ns

2.role

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: test-ns-role
  namespace: test-ns
rules:
- apiGroups: ["*"]
  resources: ['*']
  verbs: ['*']
- apiGroups: ['batch']
  resources:
  - jobs
  - cronjobs
  verbs: ['*']

3.rolebinding

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# 这个角色绑定允许 "user-test" 读取 "test-ns" 命名空间下所有权限
# 上面已经在该命名空间中创建一个名为 "test-ns-role"的角色。
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: test-user-rb
  namespace: test-ns
subjects: # 你可以指定一个以上的 "subject"
#- kind: User
#  name: test-user # "name" 是大小写敏感的
#  apiGroup: rbac.authorization.k8s.io
- kind: ServiceAccount
  name: user-test
  namespace: test-ns
roleRef: # "roleRef" 指定绑定到一个 Role/ClusterRole
   kind: Role # 必须是 Role 或 ClusterRole
   name: test-ns-role # 这必须与你想绑定的 Role 或 ClusterRole 的名字相匹配
   apiGroup: rbac.authorization.k8s.io

4.clusterrole

1
2
3
4
5
6
7
8
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: test-clusterrole
rules:
- apiGroups: ["*"]
  resources: ["*"]
  verbs: ["*"]

5.rolebinding绑定clusterrole

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
apiVersion: rbac.authorization.k8s.io/v1
# 此角色绑定使得用户 "test-ns" 能够读取 "test-ns" 名字空间中的所有权限
# 你需要一个名为 "test-clusterrole" 的 ClusterRole
kind: RoleBinding
metadata:
  name: test-user-rb-cluster
  # RoleBinding 的名字空间决定了访问权限的授予范围。
  # 这里隐含授权仅在 "development" 名字空间内的访问权限。
  namespace: test-ns
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: test-clusterrole
subjects:
- kind: ServiceAccount
  namespace: test-ns
  name: user-test-cluster

6.clusterrolebinding

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
apiVersion: rbac.authorization.k8s.io/v1
# 这个集群角色绑定允许 "test-crb" 组中的任何用户读取任意命名空间中的资源。
kind: ClusterRoleBinding
metadata:
  name: test-clusterrolebinding
subjects:
- kind: Group
  name: test-crb # 名称区分大小写
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: ClusterRole
  name: test-clusterrole
  apiGroup: rbac.authorization.k8s.io