Kubernetes-RBAC权限管理介绍

395 阅读2分钟

rbac引入了4个顶级资源对象,role, clusterrole, rolebinding, clusterrolebinding。同时其他api资源对象一样,用户可以使用kubectl或者api调用等方式操作资源对象。

1、role

一个角色就是一组权限的集合,这里的权限都是许可形式的,不存在拒绝的规则。在一个命名空间下,可以用角色来定义一个角色,如果都是集群级别,就需要使用clusterrole。

角色只能对命名空间的资源进行授权,在下面例子中定义的角色具备读取pod的权限。

    kind: Role
    apiVersion: rbac.authorization.k8s.io/v1
    metadata:
      namespace: default
      name: pod-reader
    rules:
    - apiGroups: [""]	# 空字符串表示核心api群
      resources: ["pods"]
      verbs: ["get", "watch", "list"]

rules中的参数说明如下。

  • apiGroups:支持的API组列表,例如“apiVersion:batch/v1”“apiVersion: extensions:v1beta1”“apiVersion: apps/v1beta1”等
  • resources:支持的资源对象列表,例如pods、deployments、jobs等。
  • verbs:对资源对象的操作方法列表,例如get、watch、list、delete、replace、patch等

2、clusterole 集群角色除了具有和角色一致的命名空间内资源的管理能力,因其集群级别的范围,还可以用于以下特殊元素的授权。

  • 集群范围的资源,例如Node。
  • 非资源型的路径,例如“/healthz”。
  • 包含全部命名空间的资源,例如pods(用于kubectl get pods --all-namespaces这样的操作授权)。
    kind: ClusterRole
    apiVersion: rbac.authorization.k8s.io/v1
    metadata:
      # cluseterole不受限于命名空间,所以无须设置namespace的名称
    rules:
    - apiGroups: [""]	# 空字符串表示核心api群
      resources: ["secerts"]
      verbs: ["get", "watch", "list"]

3、clusterrolebinding 角色绑定或者集群角色绑定用来把一个角色绑定到一个目标上,绑定目标可以是user,group或者sa。使用rolebinding为某个命名空间授权,使用cluseterbinding为集群范围内授权。 rolebinding可以引用role进行授。下面的例子中的rolebinding将在default命名空间中把pod-reader角色授予用户jane,这一操作可以让jane读取default命名空间中的pod:

    kind: RoleBinding
    apiVersion: rbac.authorization.k8s.io/v1
    metadata:
      name: read-pods
      namespace: default
    subjects:
    - kind: User
      name: jane
      apiGroup: rbac.authorization.k8s.io
    rules:
      kind: Role
      name: pod-reader
      apiGroups: rbac.authorization.k8s.io

    kind: ClusterRoleBinding
    apiVersion: rbac.authorization.k8s.io/v1
    metadata:
      name: read-secerts-global
    subjects:
    - kind: Group
      name: manager
      apiGroup: rbac.authorization.k8s.io
    rules:
      kind: ClusterRole
      name: secert-reader
      apiGroups: rbac.authorization.k8s.io