Kubernetes之RBAC(基於角色的訪問控制)

Kubernetes的授權是基於插件形式的,其常用的授權插件有以下幾種:

  • Node(節點認證)
  • ABAC(基於屬性的訪問控制)
  • RBAC(基於角色的訪問控制)
  • Webhook(基於http回調機制的訪問控制)
    讓一個用戶(Users)扮演一個角色(Role),角色擁有權限,從而讓用戶擁有這樣的權限,隨後在授權機制當中,只需要將權限授予某個角色,此時用戶將獲取對應角色的權限,從而實現角色的訪問控制。如圖:

Kubernetes之RBAC(基於角色的訪問控制)

基於角色的訪問控制(Role-Based Access Control, 即”RBAC”)使用”rbac.authorization.k8s.io” API Group實現授權決策,允許管理員通過Kubernetes API動態配置策略。

-

在k8s的授權機制當中,採用RBAC的方式進行授權,其工作邏輯是把對對象的操作權限定義到一個角色當中,再將用戶綁定到該角色,從而使用戶得到對應角色的權限。此種方式僅作用於名稱空間當中,這是什麼意思呢?當User1綁定到Role角色當中,User1就獲取了對該NamespaceA的操作權限,但是對NamespaceB是沒有權限進行操作的,如get,list等操作。
另外,k8s爲此還有一種集羣級別的授權機制,就是定義一個集羣角色(ClusterRole),對集羣內的所有資源都有可操作的權限,從而將User2,User3通過ClusterRoleBinding到ClusterRole,從而使User2、User3擁有集羣的操作權限。

Kubernetes之RBAC(基於角色的訪問控制)

這裏有2種綁定ClusterRoleBinding、RoleBinding。但是也可以使用RoleBinding去綁定ClusterRole。
當使用這種方式進行綁定時,用戶僅能獲取當前名稱空間的所有權限。爲什麼這麼繞呢??舉例有10個名稱空間,每個名稱空間都需要一個管理員,而該管理員的權限都是一致的。那麼此時需要去定義這樣的管理員,使用RoleBinding就需要創建10個Role,這樣顯得更加繁重。爲此當使用RoleBinding去綁定一個ClusterRole時,該User僅僅擁有對當前名稱空間的集羣操作權限,換句話說,此時只需要創建一個ClusterRole就解決了以上的需求。

-

  • 這裏要注意的是:RoleBinding僅僅對當前名稱空間有對應的權限。
    在RBAC API中,一個角色就是一組權限的集合, 權限以純粹的累加形式累積(沒有”否定”的規則)。 角色由命名空間(namespace)內的Role對象定義,而整個Kubernetes集羣範圍內有效的角色則通過ClusterRole對象實現。

角色(Role)

角色只能對命名空間內的資源進行授權,以下示例描述了”default”命名空間中定義了一個Role對象,用於授予對pod的讀訪問權限:

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

reule 中的參數說明如下:

  • apiGroups:支持的 API 組列表,例如 “apiVersion: batch/v1” “apiVersion: extensions/v1beta1” "apiVersion: apps/v1beta1" 等。
  • resource:支持的資源對象列表,例如 pods、deployments、jobs 等。
  • verbs:對資源對象的操作方法列表,例如 "get", "list", "watch", "create", "update", "patch", "delete","deletecollection" 。

集羣角色(Cluster Role)

集羣角色除了具有和角色一致的名稱空間內資源的管理能力,因其集羣級別的範圍,還可以用於以下特殊元素的授權。

  • 集羣範圍的資源,例如 Node(節點)。
  • 非資源型的路徑,例如 “/healthz”。
  • 包含全部名稱空間的資源,例如 pods(用於 kubectl get pods --all-namespaces 這樣的操作授權)。

-

下面的集羣角色可以讓用戶有權訪問任意一個或所有命名空間的 secrets(取決於其綁定方式):

kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  # 鑑於ClusterRole是作用於整個集羣範圍對象,所以這裏不需要定義"namespace"字段
  name: secret-reader
rules:
- apiGroups: [""]
  resources: ["secrets"]
  verbs: ["get", "watch", "list"]

RoleBinding與ClusterRoleBinding:

角色綁定將一個角色中定義的各種權限授予一個或者一組用戶。 角色綁定包含了一組相關主體(即subject, 包括用戶——User、用戶組——Group、或者服務賬戶——Service Account)以及對被授予角色的引用。 在命名空間中可以通過RoleBinding對象授予權限,而集羣範圍的權限授予則通過ClusterRoleBinding對象完成。

-

RoleBinding可以引用在同一命名空間內定義的Role對象。 下面示例中定義的RoleBinding對象在”default”命名空間中將”pod-reader”角色授予用戶”jane”。 這一授權將允許用戶”jane”從”default”命名空間中讀取pod。

# 以下角色綁定定義將允許用戶"jane"從"default"命名空間中讀取pod。

kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: read-pods
  namespace: default
subjects:
- kind: User          #賦予用戶jane pod-reader角色權限
  name: jane
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: pod-reader      #引用上面定義的role
  apiGroup: rbac.authorization.k8s.io

RoleBinding對象也可以引用一個ClusterRole對象用於在RoleBinding所在的命名空間內授予用戶對所引用的ClusterRole中 定義的命名空間資源的訪問權限。這一點允許管理員在整個集羣範圍內首先定義一組通用的角色,然後再在不同的命名空間中複用這些角色。(這樣做的目的是創建一個通用權限的ClusterRole,如果需要創建10個名稱空間管理員的時候只需要用RoleBinding和ClusterRole綁定即可,不用創建10個role和10個RoleBinding,只需要一個RoleBinding就搞定了)

-

例如,儘管下面示例中的RoleBinding引用的是一個ClusterRole對象,但是用戶”dave”(即角色綁定主體)還是隻能讀取”development” 命名空間中的secret(即RoleBinding所在的命名空間)。

# 以下角色綁定允許用戶"dave"讀取"development"命名空間中的secret。

kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: read-secrets
  namespace: development       # 這裏表明僅授權讀取"development"命名空間中的資源。
subjects:
- kind: User
  name: dave
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: ClusterRole
  name: secret-reader      #引用上面定義的clusterRole 名稱(clusterRole沒有指定命名空間,默認可以應用所有,但是在rolebinding時,指定了命名空間,所以只能讀取本命名空間的文件)
  apiGroup: rbac.authorization.k8s.io

最後,可以使用ClusterRoleBinding在集羣級別的所有名稱空間中授予權限。下面示例中所定義的ClusterRoleBinding 允許在用戶組”manager”中的任何用戶都可以讀取集羣中任何名稱空間中的secret。

# 以下`ClusterRoleBinding`對象允許在用戶組"manager"中的任何用戶都可以讀取集羣中任何命名空間中的secret。

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

對資源的引用

大多數資源由代表其名字的字符串表示,例如”pods”,就像它們出現在相關API endpoint的URL中一樣。然而,有一些Kubernetes API還 包含了”子資源”,比如pod的logs。在Kubernetes中,pod logs endpoint的URL格式爲:

  • GET /api/v1/namespaces/{namespace}/pods/{name}/log

-

在這種情況下,”pods”是命名空間資源,而”log”是pods的子資源。爲了在RBAC角色中表示出這一點,我們需要使用斜線來劃分資源 與子資源。如果需要角色綁定主體讀取pods以及pod log,您需要定義以下角色:

kind: Role
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  namespace: default
  name: pod-and-pod-logs-reader
rules:
- apiGroups: [""]
  resources: ["pods", "pods/log"]    #根據上面意思表示授予讀取pods和pods下log的權限
  verbs: ["get", "list"]

角色定義的例子

在以下示例中,僅截取展示了rules部分的定義。

-

允許讀取core API Group中定義的資源”pods”:

rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "list", "watch"]

允許讀寫在”extensions”和”apps” API Group中定義的”deployments”:

rules:
- apiGroups: ["extensions", "apps"]
  resources: ["deployments"]
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]

允許讀取”pods”以及讀寫”jobs”:

rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "list", "watch"]
- apiGroups: ["batch", "extensions"]
  resources: ["jobs"]
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]

允許讀取一個名爲”my-config”的ConfigMap實例(需要將其通過RoleBinding綁定從而限制針對某一個命名空間中定義的一個ConfigMap實例的訪問):

rules:
- apiGroups: [""]
  resources: ["configmaps"]
  resourceNames: ["my-config"]
  verbs: ["get"]

允許讀取core API Group中的”nodes”資源(由於Node是集羣級別資源,所以此ClusterRole定義需要與一個ClusterRoleBinding綁定纔能有效):

rules:
- apiGroups: [""]
  resources: ["nodes"]
  verbs: ["get", "list", "watch"]

允許對非資源endpoint “/healthz”及其所有子路徑的”GET”和”POST”請求(此ClusterRole定義需要與一個ClusterRoleBinding綁定纔能有效):

rules:
- nonResourceURLs: ["/healthz", "/healthz/*"]   # 在非資源URL中,'*'代表後綴通配符
  verbs: ["get", "post"]

對角色綁定主體(Subject)的引用

RoleBinding或者ClusterRoleBinding將角色綁定到角色綁定主體(Subject)。 角色綁定主體(kind指定)可以是用戶組(Group)、用戶(User)或者服務賬戶(Service Accounts)。

-

用戶由字符串表示。可以是純粹的用戶名,例如”alice”、電子郵件風格的名字,如 “[email protected]” 或者是用字符串表示的數字id。由Kubernetes管理員配置認證模塊 以產生所需格式的用戶名。對於用戶名,RBAC授權系統不要求任何特定的格式。然而,前綴system:是 爲Kubernetes系統使用而保留的,所以管理員應該確保用戶名不會意外地包含這個前綴。

-

Kubernetes中的用戶組信息由授權模塊提供。用戶組與用戶一樣由字符串表示。Kubernetes對用戶組 字符串沒有格式要求,但前綴system:同樣是被系統保留的。

-

服務賬戶(serviceAccount)擁有包含 system:serviceaccount:前綴的用戶名,並屬於擁有system:serviceaccounts:前綴的用戶組。

  • 角色綁定例子
    以下示例中,僅截取展示了RoleBinding的subjects字段。

-

一個名爲”[email protected]”的用戶:

subjects:
- kind: User
  name: "[email protected]"
  apiGroup: rbac.authorization.k8s.io

一個名爲”frontend-admins”的用戶組:

subjects:
- kind: Group
  name: "frontend-admins"
  apiGroup: rbac.authorization.k8s.io

kube-system命名空間中的默認服務賬戶:

subjects:
- kind: ServiceAccount
  name: default
  namespace: kube-system

名爲”qa”命名空間中的所有服務賬戶:

subjects:
- kind: Group
  name: system:serviceaccounts:qa
  apiGroup: rbac.authorization.k8s.io

在集羣中的所有服務賬戶:

subjects:
- kind: Group
  name: system:serviceaccounts
  apiGroup: rbac.authorization.k8s.io

所有認證過的用戶(version 1.5+):

subjects:
- kind: Group
  name: system:authenticated
  apiGroup: rbac.authorization.k8s.io 

所有未認證的用戶(version 1.5+):

subjects:
- kind: Group
  name: system:unauthenticated
  apiGroup: rbac.authorization.k8s.io

所有用戶(version 1.5+):

subjects:
- kind: Group
  name: system:authenticated
  apiGroup: rbac.authorization.k8s.io
- kind: Group
  name: system:unauthenticated
  apiGroup: rbac.authorization.k8s.io

重點注意:

在創建Rolebinding 或是Clusterrolebinding時如果是ServiceAccount則需指定Namespace字段

[root@master-1 pki]# kubectl create rolebinding heihei  --role=pods-reader   --serviceaccount=kube-system:admin --dry-run -o yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  creationTimestamp: null
  name: heihei
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: pods-reader
subjects:
- kind: ServiceAccount
  name: admin
  namespace: kube-system
#這裏的admin必須是真實存在於kubectl get sa -n kube-system中的serviceaccount
[root@master-1 pki]# kubectl describe rolebinding leader-locking-nfs-provisioner
Name:         leader-locking-nfs-provisioner
Labels:       <none>
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"rbac.authorization.k8s.io/v1","kind":"RoleBinding","metadata":{"annotations":{},"name":"leader-locking-nfs-provisioner","na...
Role:
  Kind:  Role
  Name:  leader-locking-nfs-provisioner
Subjects:
  Kind            Name             Namespace
  ----            ----             ---------
  ServiceAccount  nfs-provisioner  default

在創建Rolebinding 或是Clusterrolebinding如果是User、Group時無需指定Namespace字段

[root@master-1 pki]# kubectl describe rolebinding yedong
Name:         yedong
Labels:       <none>
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"rbac.authorization.k8s.io/v1","kind":"RoleBinding","metadata":{"annotations":{},"name":"yedong","namespace":"default"},"rol...
Role:
  Kind:  Role
  Name:  pod-reader
Subjects:
  Kind  Name    Namespace
  ----  ----    ---------
  User  yedong  

角色的創建(User --> Rolebinding --> Role)

[root@k8s-master ~]# kubectl create role -h   #查看角色創建幫助
Create a role with single rule.

Examples:
  # Create a Role named "pod-reader" that allows user to perform "get", "watch" and "list" on pods
  kubectl create role pod-reader --verb=get --verb=list --verb=watch --resource=pods

  # Create a Role named "pod-reader" with ResourceName specified
  kubectl create role pod-reader --verb=get --resource=pods --resource-name=readablepod --resource-name=anotherpod

  # Create a Role named "foo" with API Group specified
  kubectl create role foo --verb=get,list,watch --resource=rs.extensions

  # Create a Role named "foo" with SubResource specified
  kubectl create role foo --verb=get,list,watch --resource=pods,pods/status

Options:
      --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in
the template. Only applies to golang and jsonpath output formats.
      --dry-run=false: If true, only print the object that would be sent, without sending it.
  -o, --output='': Output format. One of:
json|yaml|name|go-template|go-template-file|templatefile|template|jsonpath|jsonpath-file.
      --resource=[]: Resource that the rule applies to
      --resource-name=[]: Resource in the white list that the rule applies to, repeat this flag for multiple items
      --save-config=false: If true, the configuration of current object will be saved in its annotation. Otherwise, the
annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.
      --template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The
template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
      --validate=true: If true, use a schema to validate the input before sending it
      --verb=[]: Verb that applies to the resources contained in the rule

Usage:
  kubectl create role NAME --verb=verb --resource=resource.group/subresource [--resource-name=resourcename] [--dry-run]  [options]
使用kubectl create進行創建角色,指定角色名稱,--verb指定權限,--resource指定資源或者資源組,--dry-run單跑模式並不會創建

Use "kubectl options" for a list of global command-line options (applies to all commands).

[root@k8s-master ~]# kubectl create role pods-reader --verb=get,list,watch --resource=pods --dry-run -o yaml #單跑模式查看role的定義

apiVersion: rbac.authorization.k8s.io/v1
kind: Role #資源類型
metadata:
  creationTimestamp: null
  name: pods-reader
rules:
- apiGroups:  #對那些api組內的資源進行操作
  - ""
  resources:  #對那些資源定義
  - pods
  verbs:      #操作權限定義
  - get
  - list
  - watch

[root@k8s-master ~]# cd mainfests/

[root@k8s-master mainfests]# kubectl create role pods-reader --verb=get,list,watch --resource=pods --dry-run -o yaml > role-demo.yaml

[root@k8s-master mainfests]# vim role-demo.yaml 
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: pods-reader
  namespace: default
rules:
- apiGroups:
  - ""
  resources:
  - pods
  verbs:
  - get
  - list
  - watch

[root@k8s-master mainfests]# kubectl apply -f role-demo.yaml  #角色創建
role.rbac.authorization.k8s.io/pods-reader created

[root@k8s-master mainfests]# kubectl get role
NAME          AGE
pods-reader   3s

[root@k8s-master mainfests]# kubectl describe role pods-reader
Name:         pods-reader
Labels:       <none>
Annotations:  kubectl.kubernetes.io/last-applied-configuration={"apiVersion":"rbac.authorization.k8s.io/v1","kind":"Role","metadata":{"annotations":{},"name":"pods-reader","namespace":"default"},"rules":[{"apiGroup...
PolicyRule:
  Resources  Non-Resource URLs  Resource Names  Verbs
  ---------  -----------------  --------------  -----
  pods       []                 []              [get list watch]  #此處已經定義了pods-reader這個角色對pods資源擁有get、list、watch的權限

角色的綁定

[root@k8s-master ~]# kubectl create rolebinding -h  #角色綁定創建幫助
Create a RoleBinding for a particular Role or ClusterRole.

Examples:
  # Create a RoleBinding for user1, user2, and group1 using the admin ClusterRole
  kubectl create rolebinding admin --clusterrole=admin --user=user1 --user=user2 --group=group1

Options:
      --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in
the template. Only applies to golang and jsonpath output formats.
      --clusterrole='': ClusterRole this RoleBinding should reference
      --dry-run=false: If true, only print the object that would be sent, without sending it.
      --generator='rolebinding.rbac.authorization.k8s.io/v1alpha1': The name of the API generator to use.
      --group=[]: Groups to bind to the role
  -o, --output='': Output format. One of:
json|yaml|name|templatefile|template|go-template|go-template-file|jsonpath-file|jsonpath.
      --role='': Role this RoleBinding should reference
      --save-config=false: If true, the configuration of current object will be saved in its annotation. Otherwise, the
annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.
      --serviceaccount=[]: Service accounts to bind to the role, in the format <namespace>:<name>
      --template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The
template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
      --validate=true: If true, use a schema to validate the input before sending it

Usage:
  kubectl create rolebinding NAME --clusterrole=NAME|--role=NAME [--user=username] [--group=groupname] [--serviceaccount=namespace:serviceaccountname] [--dry-run] [options]
使用kubectl create進行創建角色綁定,指定角色綁定的名稱,--role|--clusterrole指定綁定哪個角色,--user指定哪個用戶

Use "kubectl options" for a list of global command-line options (applies to all commands).

[root@k8s-master mainfests]# kubectl create rolebinding magedu-read-pods --role=pods-reader --user=magedu --dry-run -o yaml > rolebinding-demo.yaml

[root@k8s-master mainfests]# cat rolebinding-demo.yaml 
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  creationTimestamp: null
  name: magedu-read-pods
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: pods-reader
subjects:
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: magedu

[root@k8s-master mainfests]# kubectl apply -f rolebinding-demo.yaml  #創建角色綁定
rolebinding.rbac.authorization.k8s.io/magedu-read-pods created

[root@k8s-master mainfests]# kubectl describe rolebinding magedu-read-pods #查看角色綁定的信息,這裏可以看到user:magedu綁定到了pods-reader這個角色上
Name:         magedu-read-pods
Labels:       <none>
Annotations:  kubectl.kubernetes.io/last-applied-configuration={"apiVersion":"rbac.authorization.k8s.io/v1","kind":"RoleBinding","metadata":{"annotations":{},"creationTimestamp":null,"name":"magedu-read-pods","name...
Role:
  Kind:  Role
  Name:  pods-reader
Subjects:
  Kind  Name    Namespace
  ----  ----    ---------
  User  magedu  

 [root@k8s-master ~]# kubectl config use-context magedu@kubernetes #切換magedu這個用戶,並使用get獲取pods資源信息
Switched to context "magedu@kubernetes".

[root@k8s-master ~]# kubectl get pods
NAME                     READY     STATUS    RESTARTS   AGE
filebeat-ds-hxgdx        1/1       Running   1          36d
filebeat-ds-s466l        1/1       Running   2          36d
myapp-0                  1/1       Running   0          2d
myapp-1                  1/1       Running   0          2d
myapp-2                  1/1       Running   0          2d
myapp-3                  1/1       Running   0          2d
pod-sa-demo              1/1       Running   0          1d
pod-vol-demo             2/2       Running   0          3d
redis-5b5d6fbbbd-q8ppz   1/1       Running   1          4d

[root@k8s-master ~]# kubectl get pods -n ingress-nginx  #測試獲取ingress-nginx這個名稱空間的pods信息
No resources found.
Error from server (Forbidden): pods is forbidden: User "magedu" cannot list pods in the namespace "ingress-nginx"

clusterrole定義(User --> Clusterrolebinding --> Clusterrole)

[root@k8s-master mainfests]# kubectl config use-context kubernetes-admin@kubernetes  #切換會kubernetes-admin用戶
Switched to context "kubernetes-admin@kubernetes".

[root@k8s-master mainfests]# kubectl create clusterrole cluster-read --verb=get,list,watch --resource=pods -o yaml > clusterrole-demo.yaml

[root@k8s-master mainfests]# vim clusterrole-demo.yaml #定義clusterrole和權限
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: cluster-read
rules:
- apiGroups:
  - ""
  resources:
  - pods
  verbs:
  - get
  - list
  - watch
[root@k8s-master mainfests]# kubectl apply -f clusterrole-demo.yaml  #創建clusterrole
clusterrole.rbac.authorization.k8s.io/cluster-read configured

這裏我們需要切換回kubernetes-admin賬戶,是由於magedu賬戶不具備創建的權限,這也說明普通用戶是無法進行創建K8S資源的,除非進行授權。如下,我們另開一個終端,將配置到一個普通用戶ik8s上,使其使用magedu賬戶進行通信

[root@k8s-master ~]# useradd ik8s
[root@k8s-master ~]# cp -rp .kube/ /home/ik8s/
[root@k8s-master ~]# chown -R ik8s.ik8s /home/ik8s/
[root@k8s-master ~]# su - ik8s
[ik8s@k8s-master ~]$ kubectl config use-context magedu@kubernetes
Switched to context "magedu@kubernetes".
[ik8s@k8s-master ~]$ kubectl config view
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: REDACTED
    server: https://192.168.56.11:6443
  name: kubernetes
contexts:
- context:
    cluster: kubernetes
    user: kubernetes-admin
  name: kubernetes-admin@kubernetes
- context:
    cluster: kubernetes
    user: magedu
  name: magedu@kubernetes
current-context: magedu@kubernetes
kind: Config
preferences: {}
users:
- name: kubernetes-admin
  user:
    client-certificate-data: REDACTED
    client-key-data: REDACTED
- name: magedu
  user:
    client-certificate-data: REDACTED
    client-key-data: REDACTED

clusterrolebinding定義

[root@k8s-master mainfests]# kubectl get rolebinding  #獲取角色綁定信息
NAME               AGE
magedu-read-pods   1h

[root@k8s-master mainfests]# kubectl delete rolebinding magedu-read-pods #刪除前面的綁定
rolebinding.rbac.authorization.k8s.io "magedu-read-pods" deleted

[ik8s@k8s-master ~]$ kubectl get pods  #刪除後,在ik8s普通用戶上進行獲取pods資源信息,就立馬出現forbidden了
No resources found.
Error from server (Forbidden): pods is forbidden: User "magedu" cannot list pods in the namespace "default"

[root@k8s-master mainfests]# kubectl create clusterrolebinding magedu-read-all-pods --clusterrole=cluster-read --user=magedu --dry-run -o yaml > clusterrolebinding-demo.yaml

[root@k8s-master mainfests]# vim clusterrolebinding-demo.yaml  #創建角色綁定,將magedu綁定到clusterrole:magedu-read-all-pods上
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  name: magedu-read-all-pods
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-read
subjects:
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: magedu

[root@k8s-master mainfests]# kubectl get clusterrole
NAME                                                                   AGE
admin                                                                  52d
cluster-admin                                                          52d
cluster-read                                                           13m
......

[root@k8s-master mainfests]# kubectl apply -f clusterrolebinding-demo.yaml 
clusterrolebinding.rbac.authorization.k8s.io/magedu-read-all-pods created
[root@k8s-master mainfests]# kubectl get clusterrolebinding
NAME                                                   AGE
......
magedu-read-all-pods                                   10s

[root@k8s-master mainfests]# kubectl describe clusterrolebinding magedu-read-all-pods
Name:         magedu-read-all-pods
Labels:       <none>
Annotations:  kubectl.kubernetes.io/last-applied-configuration={"apiVersion":"rbac.authorization.k8s.io/v1beta1","kind":"ClusterRoleBinding","metadata":{"annotations":{},"name":"magedu-read-all-pods","namespace":""...
Role:
  Kind:  ClusterRole
  Name:  cluster-read
Subjects:
  Kind  Name    Namespace
  ----  ----    ---------
  User  magedu  

[ik8s@k8s-master ~]$ kubectl get pods  #角色綁定後在ik8s終端上進行獲取pods信息,已經不會出現forbidden了
NAME                     READY     STATUS    RESTARTS   AGE
filebeat-ds-hxgdx        1/1       Running   1          36d
filebeat-ds-s466l        1/1       Running   2          36d
myapp-0                  1/1       Running   0          2d
myapp-1                  1/1       Running   0          2d
myapp-2                  1/1       Running   0          2d
myapp-3                  1/1       Running   0          2d
pod-sa-demo              1/1       Running   0          1d
pod-vol-demo             2/2       Running   0          4d
redis-5b5d6fbbbd-q8ppz   1/1       Running   1          4d

[ik8s@k8s-master ~]$ kubectl get pods -n ingress-nginx #更換名稱空間進行查看也是可行的
NAME                                        READY     STATUS    RESTARTS   AGE
default-http-backend-7db7c45b69-nqxw9       1/1       Running   1          4d
nginx-ingress-controller-6bd7c597cb-9fzbw   1/1       Running   0          4d

[ik8s@k8s-master ~]$ kubectl delete pods pod-sa-demo  #但是進行刪除pod就無法進行,因爲在授權時是沒有delete權限的
Error from server (Forbidden): pods "pod-sa-demo" is forbidden: User "magedu" cannot delete pods in the namespace "default"

從上面的實驗,我們可以知道對用戶magedu進行集羣角色綁定,用戶magedu將會獲取對集羣內所有資源的對應權限。

User --> Rolebinding --> Clusterrole

將maedu通過rolebinding到集羣角色cluster-read當中,此時,magedu僅作用於當前名稱空間的所有pods資源的權限

[root@k8s-master mainfests]# kubectl delete clusterrolebinding magedu-read-all-pods
clusterrolebinding.rbac.authorization.k8s.io "magedu-read-all-pods" deleted

[root@k8s-master mainfests]# kubectl create rolebinding magedu-read-pods --clusterrole=cluster-read --user=magedu --dry-run -o yaml > rolebinding-clusterrole-demo.yaml

[root@k8s-master mainfests]# vim rolebinding-clusterrole-demo.yaml 
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: magedu-read-pods
  namespace: default
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-read
subjects:
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: magedu

[root@k8s-master mainfests]# kubectl apply -f rolebinding-clusterrole-demo.yaml 
rolebinding.rbac.authorization.k8s.io/magedu-read-pods created

[ik8s@k8s-master ~]$ kubectl get pods
NAME                     READY     STATUS    RESTARTS   AGE
filebeat-ds-hxgdx        1/1       Running   1          36d
filebeat-ds-s466l        1/1       Running   2          36d
myapp-0                  1/1       Running   0          2d
myapp-1                  1/1       Running   0          2d
myapp-2                  1/1       Running   0          2d
myapp-3                  1/1       Running   0          2d
pod-sa-demo              1/1       Running   0          1d
pod-vol-demo             2/2       Running   0          4d
redis-5b5d6fbbbd-q8ppz   1/1       Running   1          4d

[ik8s@k8s-master ~]$ kubectl get pods -n ingress-nginx
No resources found.
Error from server (Forbidden): pods is forbidden: User "magedu" cannot list pods in the namespace "ingress-nginx"

默認角色與默認角色綁定

API Server會創建一組默認的ClusterRole和ClusterRoleBinding對象。 這些默認對象中有許多包含system:前綴,表明這些資源由Kubernetes基礎組件”擁有”。 對這些資源的修改可能導致非功能性集羣(non-functional cluster)。一個例子是system:node ClusterRole對象。 這個角色定義了kubelets的權限。如果這個角色被修改,可能會導致kubelets無法正常工作。

所有默認的ClusterRole和ClusterRoleBinding對象都會被標記爲kubernetes.io/bootstrapping=rbac-defaults。

-

每次啓動時,API Server都會更新默認ClusterRole所缺乏的各種權限,並更新默認ClusterRoleBinding所缺乏的各個角色綁定主體。 這種自動更新機制允許集羣修復一些意外的修改。由於權限和角色綁定主體在新的Kubernetes釋出版本中可能變化,這也能夠保證角色和角色 綁定始終保持是最新的。

-

如果需要禁用自動更新,請將默認ClusterRole以及ClusterRoleBinding的rbac.authorization.kubernetes.io/autoupdate 設置成爲false。 請注意,缺乏默認權限和角色綁定主體可能會導致非功能性集羣問題。

-

自Kubernetes 1.6+起,當集羣RBAC授權器(RBAC Authorizer)處於開啓狀態時,可以啓用自動更新功能

發現類角色

下面是一些默認Clusterrole綁定默認的Clusterrolebinding

Kubernetes之RBAC(基於角色的訪問控制)

面向用戶的角色

一些默認角色並不包含system:前綴,它們是面向用戶的角色。 這些角色包含超級用戶角色(cluster-admin),即旨在利用ClusterRoleBinding(cluster-status)在集羣範圍內授權的角色, 以及那些使用RoleBinding(admin、edit和view)在特定命名空間中授權的角色。

Kubernetes之RBAC(基於角色的訪問控制)

核心組件角色

Kubernetes之RBAC(基於角色的訪問控制)

其它組件角色

Kubernetes之RBAC(基於角色的訪問控制)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章