0%

k8s权限使用【ServiceAccount、Role、RoleBinding使用】

需求:需要为每个项目组在K8s集群中创建不同的namespace,然后为这个namespace创建单独的ServiceAccount,这个ServiceAccount需要拥有这个namespace的完全控制权。以下均通过YAML文件的方式创建。

创建namespace

打个标签,代表是测试用的

apiVersion: v1
kind: Namespace
metadata:
  name: test-deri
  labels:
    name: test

创建ServiceAccount

注意指定namespace

apiVersion: v1
kind: ServiceAccount
metadata:
  name: test-deri
  namespace: test-deri

创建role

创建role,两种方式:

  • 第一种,需要依次指定apiGroupsresourcesverbs,便于权限的细粒度控制,
  • 第二种通过通用符 * 设置所有权限,非常方便。

第一种

kind: Role
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  namespace: test-deri
  name: pod-reader
rules:
  - apiGroups: [""] # The API group "" indicates the core API Group.
    resources:
    - configmaps
    - secrets
    - nodes
    - nodes/metrics
    - nodes/stats
    - nodes/log
    - nodes/spec
    - nodes/proxy
    - pods
    - services
    - resourcequotas
    - replicationcontrollers
    - limitranges
    - persistentvolumeclaims
    - persistentvolumes
    - namespaces
    - endpoints
    - proxy
    verbs:
    - list
    - watch
    - get
  - apiGroups:
    - extensions
    resources:
    - daemonsets
    - deployments
    - replicasets
    - ingresses
    verbs:
    - list
    - watch
  - apiGroups:
    - apps
    resources:
    - statefulsets
    - daemonsets
    - deployments
    - replicasets
    verbs:
    - list
    - watch
  - apiGroups:
    - batch
    resources:
    - cronjobs
    - jobs
    verbs:
    - list
    - watch
  - apiGroups:
    - autoscaling
    resources:
    - horizontalpodautoscalers
    verbs:
    - list
    - watch
  - apiGroups:
    - authentication.k8s.io
    resources:
    - tokenreviews
    verbs:
    - create
  - apiGroups:
    - authorization.k8s.io
    resources:
    - subjectaccessreviews
    verbs:
    - create
    nonResourceURLs: []

第二种

kind: Role
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  namespace: test-deri
  name: pod-reader
rules:
  - apiGroups:
    - '*'
    resources:
    - '*'
    verbs:
    - '*'

创建RoleBinding

将创建的roleserviceaccount绑定

# This role binding allows "test-deri" to read pods in the namespace "test-deri"
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: read-pods
  namespace: test-deri
subjects:
  - kind: ServiceAccount # May be "User", "Group" or "ServiceAccount"
    name: test-deri
roleRef:
  kind: Role
  name: pod-reader
  apiGroup: rbac.authorization.k8s.io

查看token

查看创建ServiceAccount时自动创建的Secret Token,查看ServiceAccount名称开头的token

kubectl get secret -n test-deri
kubectl describe secret test-deri-token-xxxxx -n test-deri

使用该token登录dashboard,可以查看、使用刚刚创建的namespace,但是没有权限访问别的namespace,这样就做到了权限控制。