0%

kubernetes 中的RBAC

kubernetes RBAC

角色绑定将角色映射到一个用户或者一组用户,把角色在命名空间中对资源的权限授权给这些用户。ClusterRoleBinding(集群角色绑定)允许授权用户ClusterRole的在整个集群中的授权访问。

RBAC API定义了四个资源对象用于描述角色和权限、角色和用户的关系:

  • Role
  • ClusterRole
  • RoleBinding
  • ClusterRoleBinding

Role 和 ClusterRole

描述角色和权限的关系

Roles 是限定在某个Namespace下的
kubectl get roles --all-namespaces

ClusterRole 是整个集群范围的
kubectl get clusterroles

资源示例

一条规则由 apiGroupsresourcesverbs 共同组成,结构如下

1
2
3
4
5
6
7
8
9
kind: Role
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
namespace: default
name: pod-reader
rules:
- apiGroups: [""] # "" indicates the core API group
resources: ["pods"]
verbs: ["get", "watch", "list"]

ClusterRole 在资源结构上类似

1
2
3
4
5
6
7
8
9
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
# 不能有"namespace"
name: secret-reader
rules:
- apiGroups: [""]
resources: ["secrets"]
verbs: ["get", "watch", "list"]

RoleBinding 和 ClusterRoleBinding

描述 subjects (包含users, groups, service accounts)和 角色的关系

RoleBinding 是限定在某个Namespace下的
kubectl get rolebinding --all-namespaces

ClusterRoleBinding 是整个集群范围的
kubectl get clusterrolebinding

资源示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# This role binding allows "jane" to read pods in the "default" namespace.
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: read-pods
namespace: default
subjects:
- kind: User
name: jane
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role
name: pod-reader
apiGroup: rbac.authorization.k8s.io
1
2
3
4
5
6
7
8
9
10
11
12
13
# This cluster role binding allows anyone in the "manager" group to read secrets in any namespace.
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: read-secrets-global
subjects:
- kind: Group
name: manager
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: ClusterRole
name: secret-reader
apiGroup: rbac.authorization.k8s.io

subjects 使用示例

subjects 是访问api 的主体
之前提到 subjects 包含users, groups, service accounts 三种类型,下面展示下具体写法

1
2
3
4
5
6
7
8
9
10
subjects:
- kind: User
name: "nil@example.com"
apiGroup: rbac.authorization.k8s.io
- kind: Group
name: "frontend-admins"
apiGroup: rbac.authorization.k8s.io
- kind: ServiceAccount
name: default
namespace: kube-system

我们现有环境,k8s 组件访问 apiserver 使用基于证书的认证方式(双向),apiserver 接受请求时会从client 证书中提取
CNO字段,分别作为 subjects 中的 UserGroup

下面是kube-proxy证书配置的示例,配内容可以查阅文档

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"CN": "system:kube-proxy",
"hosts": [""],
"key": {
"algo": "rsa",
"size": 2048
},
"names": [
{
"O": "system:nodes"
}
]
}

至于集群内访问 apiserver 均使用service accounts 来表示身份

Kubernetes中默认的Role和RoleBinding

可以使用以下两个指令查看默认的权限设置
kubectl get clusterrole -l kubernetes.io/bootstrapping=rbac-defaults

kubectl get clusterrolebinding -l kubernetes.io/bootstrapping=rbac-defaults

创建clusterrolebinding 示例

1
2
3
4
5
kubectl create clusterrolebinding admin \
--clusterrole=cluster-admin \
--user=system:kube-controller-manager \
--user=system:kube-scheduler \
--group=system:kube-controller-manager