(十二)Kubernetes 認證、受權與准入控制

訪問控制概述

API Server做爲Kubernetes集羣系統的網關,是訪問和管理資源對象的惟一入口;包括kube-controller-managerkube-schedulerkubeletkube-proxy等集羣基礎組件、CoreDNS等附加組件和kubectl命令等都須要通過網關才能進行正常的訪問和管理。每一次的訪問請求都須要進行合法性檢驗,包括用戶身份驗證、操做權限驗證及操做規範驗證等,須要經過一系列驗證經過以後才能訪問或存儲數據到etcd中。以下圖所示nginx

經過上圖能夠看出訪問kubernetes集羣的資源須要三關:認證、受權、准入控制;API Server處理請求的過程當中,認證插件負責鑑定用戶身份,受權插件用於操做權限許可鑑別,而准入插件則用於在資源對象的建立、刪除、更新或鏈接(proxy)操做時實現更精細的許可檢查。vim

普通用戶若要安全訪問集羣API Server,每每須要證書、Token或者用戶名+密碼。api

ServiceAccount

Servic Account(服務帳號):是指由Kubernetes API管理的帳號,用於爲Pod之中的服務進程在訪問Kubernetes API時提供身份標識。Service Account一般綁定於特定的名稱空間,由API Server建立,或者經過API調用手動建立。安全

User Account(用戶帳號):獨立於Kubernetes以外的其餘服務管理用戶帳號,例如由管理員分發祕鑰、Keystone一類的用戶存儲(帳號庫)、甚至是保函有用戶名和密碼列表的文件等。app

  • User Account是爲人設計的,而Service Account則是爲Pod中的進程調用Kubernetes API而設計;frontend

  • User Account是跨namespace的,而Service Account則是僅侷限它所在的namespace測試

  • 每一個namespace都會自動建立一個default service accountspa

在建立Pod資源時,若是沒有指定一個service account,系統會自動在與該Pod相同的namespace下爲其指派一個default service account。而podapiserver之間進行通訊的帳號,稱爲serviceAccountName。以下:插件

[root@k8s-master ~]# kubectl get pods  
NAME                  READY   STATUS    RESTARTS   AGE
nginx-statefulset-0   1/1     Running   0          43h
nginx-statefulset-1   1/1     Running   0          43h
nginx-statefulset-2   1/1     Running   0          43h
nginx-statefulset-3   1/1     Running   0          43h
[root@k8s-master ~]# kubectl get pods/nginx-statefulset-0 -o yaml |grep "serviceAccountName"
  serviceAccountName: default
[root@k8s-master ~]# kubectl describe pods/nginx-statefulset-0
Name:           nginx-statefulset-0
Namespace:      default
......
Volumes:
  default-token-blm9l:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-blm9l
    Optional:    false

經過上面能夠看出每一個Pod不管定義與否都會有一個存儲卷,這個存儲卷爲default-token-* token令牌,這就是Pod和serviceaccount認證信息。經過secret進行定義,因爲認證信息屬於敏感信息,因此須要保存在secret資源當中,並以存儲卷的方式掛載到Pod當中。從而讓Pod內運行的應用經過對應的secret中的信息來鏈接apiserver,並完成認證。每一個namespace中都有一個默認的叫作default的service account資源。進行查看名稱空間內的secret,也能夠看到對應的default-token。讓當前名稱空間中全部的pod在鏈接apiserver時可使用的預製認證信息,從而保證pod之間的通訊。

Service Account建立

[root@k8s-master ~]# kubectl get sa     #查看serviceaccount資源
NAME      SECRETS   AGE
default   1         7d19h
[root@k8s-master ~]# kubectl create serviceaccount admin    #建立一個名爲admin的serviceaccount資源
serviceaccount/admin created
[root@k8s-master ~]# kubectl get sa     #查看serviceaccount資源
NAME      SECRETS   AGE
admin     1         7s
default   1         7d19h
[root@k8s-master ~]# kubectl describe sa/admin    #查看serviceaccount資源admin的詳細信息,能夠看出已經自動生成了一個Tokens:admin-token-lc826
Name:                admin
Namespace:           default
Labels:              <none>
Annotations:         <none>
Image pull secrets:  <none>
Mountable secrets:   admin-token-lc826
Tokens:              admin-token-lc826
Events:              <none>
[root@k8s-master ~]# kubectl get secret    #查看secret,能夠查看也生成了一個admin-token-lc826的secret資源
NAME                  TYPE                                  DATA   AGE
admin-token-lc826     kubernetes.io/service-account-token   3      50s
......

Pod中引用service accountssr

每一個Pod對象都可附加其所屬名稱空間中的一個Service Account資源,且只能附加一個。不過,一個Service Account資源可由所屬名稱空間中的多個Pod對象共享使用。建立Pod時,經過「spec.serviceAccountName」進行定義。示例以下:

[root@k8s-master manfests]# vim pod-sa-demo.yaml    #編輯資源清單文件
apiVersion: v1
kind: Pod
metadata:
  name: pod-sa-demo
  namespace: default
  labels:
    app: myapp
    tier: frontend
spec:
  containers:
  - name: myapp
    image: ikubernetes/myapp:v1
    ports:
    - name: http
      containerPort: 80
  serviceAccountName: admin    #指定serviceAccount資源名稱
  
[root@k8s-master manfests]# kubectl apply -f pod-sa-demo.yaml 
pod/pod-sa-demo created
[root@k8s-master manfests]# kubectl get pods -l app=myapp
NAME          READY   STATUS    RESTARTS   AGE
pod-sa-demo   1/1     Running   0          9s
[root@k8s-master manfests]# 
[root@k8s-master manfests]# kubectl describe pods/pod-sa-demo
Name:         pod-sa-demo
Namespace:    default
......
Volumes:
  admin-token-lc826:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  admin-token-lc826      #這裏能夠看出掛載token就是上面建立的sa所生成的那個。
    Optional:    false
......

客戶端配置文件kubeconfig

包括kubectlkubeletkube-controller-manager等在內的API Server的各種客戶端均可以使用kubeconfig配置文件提供接入多個集羣的相關配置信息,包括API ServerURL及認證信息等,並且可以設置成不一樣的上下文環境,並在各環境之間快速切換。

kubernetes集羣中,每個用戶對資源的訪問都須要經過apiserver進行通訊認證才能進行訪問的,那麼在此機制當中,對資源的訪問能夠是token,也能夠是經過配置文件的方式進行保存和使用認證信息,能夠經過kubectl config進行查看和配置。以下:

[root@k8s-master]# kubectl config view
apiVersion: v1
clusters:    #集羣列表
- cluster:
    certificate-authority-data: DATA+OMITTED
    server: https://192.168.1.31:6443
  name: kubernetes
contexts:    #上下文列表
- context:
    cluster: kubernetes
    user: kubernetes-admin
  name: kubernetes-admin@kubernetes
current-context: kubernetes-admin@kubernetes
kind: Config
preferences: {}
users:    #用戶列表
- name: kubernetes-admin
  user:
    client-certificate-data: REDACTED
    client-key-data: REDACTED
  • cluster:集羣列表,包含訪問API ServerURL和所屬集羣的名稱等。

  • users:用戶列表,包含訪問API Server時的用戶名和認證信息。

  • contexts:kubelet的可用上下文列表,由用戶列表中的某特定用戶名稱和集羣列表中的某特定集羣名稱組合而成。

經過kubeadm部署的kubernetes集羣默認提供了擁有集羣管理權限的kubeconfig配置文件/etc/kubernetes/admin.conf,它可被複制到任何有着kubectl的主機上以用於管理整個集羣。還能夠建立基於SSL/TLS認證的自定義帳號,以授予非管理員級別的集羣資源使用權限。配置過程由兩部分組成,一是爲用戶建立專用私鑰及證書文件,而是將其配置與kubeconfig文件中。

自建證書和帳號進行訪問apiserver示例

1)爲目標用戶帳號kube-user1建立私鑰及證書文件,保存於/etc/kubernetes/pki目錄中

(1)生成私鑰,權限設置爲600
[root@k8s-master ~]# cd /etc/kubernetes/pki/
[root@k8s-master pki]# (umask 077; openssl genrsa -out kube-user1.key 2048)
Generating RSA private key, 2048 bit long modulus
...................................................................................................................+++
.+++
e is 65537 (0x10001)
[root@k8s-master pki]# ll kube-user1.key 
-rw------- 1 root root 1679 10月 16 15:01 kube-user1.key

(2)建立證書籤署請求,-subj選項中的CN的值將被kubeconfig做爲用戶名使用,O的值將被識別爲用戶組
[root@k8s-master pki]# openssl req -new -key kube-user1.key -out kube-user1.csr -subj "/CN=kube-user1/O=kubernetes"

(3)基於kubeadm安裝Kubernetes集羣時生成的CA簽署證書,這裏設置其有效時長爲3650天
[root@k8s-master pki]# openssl x509 -req -in kube-user1.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out kube-user1.crt -days 3650
Signature ok
subject=/CN=kube-user1/O=kubernetes
Getting CA Private Key

(4)驗證證書信息
[root@k8s-master pki]# openssl x509 -in kube-user1.crt -text -noout

2)使用默認的管理員kubernetes-admin@kubernetes爲新建的kube-user1設定kube-config配置文件。配置結果默認保存於當前系統用戶的.kube/config文件中。

(1)添加用戶到認證
[root@k8s-master pki]# kubectl config set-credentials kube-user1 --embed-certs=true --client-certificate=/etc/kubernetes/pki/kube-user1.crt --client-key=/etc/kubernetes/pki/kube-user1.key
User "kube-user1" set.
(2)配置context,用來組合cluster和credentials,即訪問的集羣的上下文
[root@k8s-master pki]# kubectl config set-context kube-user1@kubernetes --cluster=kubernetes --user=kube-user1
Context "kube-user1@kubernetes" created.
(3)查看配置文件信息
[root@k8s-master pki]# kubectl config view
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: DATA+OMITTED
    server: https://192.168.1.31:6443
  name: kubernetes
contexts:
- context:
    cluster: kubernetes
    user: kube-user1
  name: kube-user1@kubernetes
- context:
    cluster: kubernetes
    user: kubernetes-admin
  name: kubernetes-admin@kubernetes
current-context: kubernetes-admin@kubernetes
kind: Config
preferences: {}
users:
- name: kube-user1
  user:
    client-certificate-data: REDACTED
    client-key-data: REDACTED
- name: kubernetes-admin
  user:
    client-certificate-data: REDACTED
    client-key-data: REDACTED
(4)指定要使用的上下文,切換爲kube-user1訪問集羣
[root@k8s-master pki]# kubectl config use-context kube-user1@kubernetes
Switched to context "kube-user1@kubernetes".
(5)測試訪問kubernetes的資源
[root@k8s-master pki]# kubectl get pods 
Error from server (Forbidden): pods is forbidden: User "kube-user1" cannot list resource "pods" in API group "" in the namespace "default"

從上面的測試,當切換爲kube-user1用戶進行訪問集羣時,因爲kube-user1用戶沒有管理集羣的權限,因此在獲取pods資源信息時,會提示Forbidden。

RBAC-基於角色的訪問控制

介紹RBAC

RBACRole-Based Access Control,基於角色的訪問控制)是一種新型、靈活且使用普遍的訪問控制機制,它將權限授予「角色」(role)之上,這一點有別於傳統訪問機制中將權限直接賦予使用者的方式。

RBAC中,用戶(User)就是一個能夠獨立訪問計算機系統中的數據或者用數據表示的其餘資源的主體(Subject)。角色是指一個組織或任務中的工做或者位置,它表明一種權利、資格和責任。許可(Permission)就是容許對一個或多個客體(Object)執行的操做。一個用戶能夠經受權而擁有多個角色,一個角色可由多個用戶構成;每一個角色可擁有多種許可,每一個許可也可受權給多個不一樣的角色。每一個操做可施加於多個客體(受控對象),每一個客體也能夠接受多個操做。

RBAC簡單來講就是讓一個用戶(Users)扮演一個角色(Role),角色擁有權限,讓用戶綁定該角色;隨後在受權機制中,只須要將權限受權給某個角色,此時用戶將獲取對應角色的權限,從而實現角色的訪問控制。

RBAC受權規則

RBAC受權規則是經過四種資源來進行配置的,他們能夠分爲兩個組:

  • Role(角色)和ClusterRole(集羣角色),它們指定了在資源上能夠執行哪些動做。

  • RoleBinding(角色綁定)和ClusterRoleBinding(集羣角色綁定),它們將上述角色綁定到特定的用戶、組或ServiceAccounts上。

角色定義了能夠作什麼操做,而綁定定義了誰能夠作這些操做,以下圖所示:

綁定關係:

角色和集羣角色,或者角色綁定和集羣角色綁定之間的區別在於角色和角色綁定是名稱空間級別,而集羣角色和集羣角色綁定是集羣級別的資源。

  • RoleBind--Role:kubernetes受權機制中,採用RBAC的方式進行受權,把對象的操做權限定義到一個角色當中,而將用戶綁定到該角色,從而使得用戶獲得對應角色的權限。好比下圖,當用戶(User1)綁定到Role角色當中,User1就獲取了對應的NamespaceA的操做權限,可是對於NamespaceB是沒有權限進行操做的。如getlist等操做。

  • ClusterRoleBind--ClusterRole:集羣級別的受權,定義一個集羣角色(ClusterRole),對集羣內的全部資源都有可操做的權限,以下圖(只看藍色的線鏈接),當用戶(User1)經過ClusterRolebindingClusterRole,從而User1遍擁有了集羣的操做權限。

  • RoleBind-ClusterRole:這種方式進行綁定時,用戶僅能獲取當前名稱空間的全部權限。爲何這麼繞呢?? 舉例有10個名稱空間,每一個名稱空間都須要一個管理員,而每一個管理員的權限是一致的。那麼此時須要去定義這樣的管理員,使用RoleBinding就須要建立10Role,這樣顯得更加繁重。爲了當使用RoleBinding去綁定一個ClusterRole時,該User僅僅擁有對當前名稱空間的集羣操做權限,也就是此時只須要建立一個ClusterRole就解決了以上的需求。好比下圖中的User2User3用戶雖然綁定了ClusterRole,可是他們也只有本身的名稱空間NamespaceB中權限。

Kubernetes RBAC示例

這裏因爲要切換用戶,使用root用戶同時不停的在kubernetes-admin用戶和上面建立的kube-user1用戶之間進行測試。故這裏建立一個測試用戶打開另一個終端進行測試。

[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 kube-user1@kubernetes
Switched to context "kube-user1@kubernetes".
[ik8s@k8s-master ~]$ kubectl config view
......
current-context: kube-user1@kubernetes    #這裏能夠看到當前已經切換到kube-user1用戶了
......
[ik8s@k8s-master ~]$ kubectl get pods     #測試kube-user1用戶的權限,能夠看出目前它沒有任何權限
Error from server (Forbidden): pods is forbidden: User "kube-user1" cannot list resource "pods" in API group "" in the namespace "default"

User --> Rolebinding --> Role

1)角色(Role)建立。(說明:一個Role對象只能用於授予對某一單一名稱空間中資源的訪問權限)

[root@k8s-master ~]# kubectl create role -h    #查看role建立幫助
......
Usage:
  kubectl create role NAME --verb=verb --resource=resource.group/subresource
[--resource-name=resourcename] [--dry-run] [options]
--verb    #指定權限
--resource    #指定資源或者資源組
--dry-run    #幹跑模式並不會建立

[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 manfests/
[root@k8s-master manfests]# kubectl create role pods-reader --verb=get,list,watch --resource=pods --dry-run -o yaml > role-demo.yaml

[root@k8s-master manfests]# 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 manfests]# kubectl apply -f role-demo.yaml   
role.rbac.authorization.k8s.io/pods-reader created
[root@k8s-master manfests]# kubectl get role
NAME          AGE
pods-reader   4s
[root@k8s-master manfests]# 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...
PolicyRule:
  Resources  Non-Resource URLs  Resource Names  Verbs
  ---------  -----------------  --------------  -----
  pods       []                 []              [get list watch]    #這裏表示當前定義了pods-reader這個角色對pods資源擁有get、list、watch的權限。

2)角色的綁定。(RoleBinding能夠引用在同一名稱空間定義的Role對象)

[root@k8s-master manfests]# kubectl create rolebinding -h    #查看rolebinding建立幫助
......
Usage:
  kubectl create rolebinding NAME --clusterrole=NAME|--role=NAME
[--user=username] [--group=groupname]
[--serviceaccount=namespace:serviceaccountname] [--dry-run] [options]
--role    #指定role的名字
--user    #指定哪一個用戶

[root@k8s-master manfests]# kubectl create rolebinding kube-user1-read-pods --role=pods-reader --user=kube-user1 --dry-run -o yaml    #幹跑模式查看rolebinding的定義格式
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding    #資源類型
metadata:
  creationTimestamp: null
  name: kube-user1-read-pods    #資源名稱
roleRef:    #指定role
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: pods-reader
subjects:    #指定user
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: kube-user1
  
[root@k8s-master manfests]# kubectl create rolebinding kube-user1-read-pods --role=pods-reader --user=kube-user1 --dry-run -o yaml > rolebinding-demo.yaml
[root@k8s-master manfests]# vim rolebinding-demo.yaml    #編輯資源清單文件
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: kube-user1-read-pods
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: pods-reader
subjects:
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: kube-user1

[root@k8s-master manfests]# kubectl apply -f rolebinding-demo.yaml 
rolebinding.rbac.authorization.k8s.io/kube-user1-read-pods created
[root@k8s-master manfests]# kubectl get rolebinding
NAME                   AGE
kube-user1-read-pods   9s
[root@k8s-master manfests]# kubectl describe rolebinding kube-user1-read-pods    #查看角色綁定的信息,這裏能夠看到user kube-user1綁定到了pods-reader這個角色上。
Name:         kube-user1-read-pods
Labels:       <none>
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"rbac.authorization.k8s.io/v1","kind":"RoleBinding","metadata":{"annotations":{},"name":"kube-user1-read-pods","namespace":"...
Role:
  Kind:  Role
  Name:  pods-reader
Subjects:
  Kind  Name        Namespace
  ----  ----        ---------
  User  kube-user1 

3)權限測試

這時候咱們使用kube-user1用戶進行測試
[ik8s@k8s-master ~]$ kubectl config use-context kube-user1@kubernetes   #若是沒有切換到該kube-user1用戶,經過kubectl config use-context進行切換

[ik8s@k8s-master ~]$ kubectl get pods     #在default名稱空間獲取pods信息
NAME                  READY   STATUS    RESTARTS   AGE
nginx-statefulset-0   1/1     Running   0          3d
nginx-statefulset-1   1/1     Running   0          3d
nginx-statefulset-2   1/1     Running   0          3d
nginx-statefulset-3   1/1     Running   0          3d
pod-sa-demo           1/1     Running   0          27h

[ik8s@k8s-master ~]$ kubectl get pods -n kube-system    #測試獲取kube-system名稱空間中的pods
Error from server (Forbidden): pods is forbidden: User "kube-user1" cannot list resource "pods" in API group "" in the namespace "kube-system"

從上面的操做能夠看出,role的定義和綁定,僅做用於當前名稱空間,在獲取別的名稱空間好比kube-system名稱空間時,同樣會出現Forbidden

User --> ClusterRolebinding --> ClusterRole

1)ClusterRole定義

ClusterRole資源對象能夠授予與Role資源對象相同的權限,但因爲它們屬於集羣範圍的對象,也可使用它們授予對如下幾種資源的訪問權限:

  • 集羣範圍資源(例如節點,即Node

  • 非資源類型endpoint(例如/api/healthz等。)

  • 跨全部名稱空間的名稱空間資源(例如pod,運行kubectl get pods --all-namespaces來查詢集羣中全部的pod

[root@k8s-master manfests]# kubectl create clusterrole -h    #查看clusterrole建立幫助
......
Usage:
  kubectl create clusterrole NAME --verb=verb --resource=resource.group
[--resource-name=resourcename] [--dry-run] [options]
--verb    #指定權限
--resource    #指定資源或者資源組

[root@k8s-master manfests]# kubectl create clusterrole cluster-reader --verb=get,list,watch --resource=pods --dry-run -o yaml    #幹跑模式查看clusterrole的定義格式
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  creationTimestamp: null
  name: cluster-reader
rules:
- apiGroups:
  - ""
  resources:
  - pods
  verbs:
  - get
  - list
  - watch

[root@k8s-master manfests]# kubectl create clusterrole cluster-reader --verb=get,list,watch --resource=pods --dry-run -o yaml > clusterrole-demo.yaml
[root@k8s-master manfests]# vim clusterrole-demo.yaml    #編輯資源清單
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: cluster-reader
rules:
- apiGroups:
  - ""
  resources:
  - pods
  verbs:
  - get
  - list
  - watch

[root@k8s-master manfests]# kubectl apply -f clusterrole-demo.yaml    #建立clusterrole
clusterrole.rbac.authorization.k8s.io/cluster-reader created
[root@k8s-master manfests]# kubectl get clusterrole |grep "cluster-reader"
cluster-reader                                                         19s
[root@k8s-master manfests]# kubectl describe clusterrole/cluster-reader
Name:         cluster-reader
Labels:       <none>
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"rbac.authorization.k8s.io/v1","kind":"ClusterRole","metadata":{"annotations":{},"name":"cluster-reader"},"rules":[{"apiGrou...
PolicyRule:
  Resources  Non-Resource URLs  Resource Names  Verbs
  ---------  -----------------  --------------  -----
  pods       []                 []              [get list watch]

2)ClusterRoleBinding定義

#這裏仍是使用kube-user1用戶,因此先將上面的角色綁定信息刪除
[root@k8s-master manfests]# kubectl get rolebinding     #查看角色綁定信息
NAME                   AGE
kube-user1-read-pods   27m
[root@k8s-master manfests]# kubectl delete rolebinding kube-user1-read-pods     #刪除前面的綁定
rolebinding.rbac.authorization.k8s.io "kube-user1-read-pods" delete
[ik8s@k8s-master ~]$ kubectl get pods     #刪除後再用kube-user1用戶獲取pods資源信息,就立馬出現Forbidden了
Error from server (Forbidden): pods is forbidden: User "kube-user1" cannot list resource "pods" in API group "" in the namespace "default"


[root@k8s-master manfests]# kubectl create clusterrolebinding -h
Usage:
  kubectl create clusterrolebinding NAME --clusterrole=NAME [--user=username]
[--group=groupname] [--serviceaccount=namespace:serviceaccountname] [--dry-run]
[options]
--clusterrole    #指定clusterrole
--user    #指定用戶

[root@k8s-master manfests]# kubectl create clusterrolebinding kube-user1-read-all-pods --clusterrole=cluster-reader --user=kube-user1 --dry-run -o yaml
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  creationTimestamp: null
  name: kube-user1-read-all-pods
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-reader
subjects:
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: kube-user1
  
[root@k8s-master manfests]# kubectl create clusterrolebinding kube-user1-read-all-pods --clusterrole=cluster-reader --user=kube-user1 --dry-run -o yaml > clusterrolebinding-demo.yaml
[root@k8s-master manfests]# vim clusterrolebinding-demo.yaml    #編輯資源清單文件
cat clusterrolebinding-demo.yaml
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  name: kube-user1-read-all-pods
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-reader
subjects:
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: kube-user1

[root@k8s-master manfests]# kubectl apply -f clusterrolebinding-demo.yaml     #建立clusterrolebinding
clusterrolebinding.rbac.authorization.k8s.io/kube-user1-read-all-pods created
[root@k8s-master manfests]# kubectl get clusterrolebinding/kube-user1-read-all-pods
NAME                       AGE
kube-user1-read-all-pods   25s
[root@k8s-master manfests]# kubectl describe clusterrolebinding/kube-user1-read-all-pods    #查看clusterrolebinding資源kube-user1-read-all-pods詳細信息,能夠看到kube-user1用戶已經綁定到clusterrole資源cluster-reader上了。
Name:         kube-user1-read-all-pods
Labels:       <none>
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"rbac.authorization.k8s.io/v1beta1","kind":"ClusterRoleBinding","metadata":{"annotations":{},"name":"kube-user1-read-all-pod...
Role:
  Kind:  ClusterRole
  Name:  cluster-reader
Subjects:
  Kind  Name        Namespace
  ----  ----        ---------
  User  kube-user1

3)權限測試

[ik8s@k8s-master ~]$ kubectl get pods     #角色綁定後再次獲取pods信息,已經能夠正常查看
NAME                  READY   STATUS    RESTARTS   AGE
nginx-statefulset-0   1/1     Running   0          3d1h
nginx-statefulset-1   1/1     Running   0          3d1h
nginx-statefulset-2   1/1     Running   0          3d1h
nginx-statefulset-3   1/1     Running   0          3d1h
pod-sa-demo           1/1     Running   0          28h

[ik8s@k8s-master ~]$ kubectl get pods -n kube-system    #切換名稱空間也是能夠查看的
NAME                                 READY   STATUS    RESTARTS   AGE
coredns-bccdc95cf-9gsn8              1/1     Running   0          8d
coredns-bccdc95cf-x7m8g              1/1     Running   0          8d
etcd-k8s-master                      1/1     Running   0          8d
kube-apiserver-k8s-master            1/1     Running   0          8d
kube-controller-manager-k8s-master   1/1     Running   0          8d
kube-flannel-ds-amd64-gg55s          1/1     Running   0          8d
kube-flannel-ds-amd64-ssr7j          1/1     Running   5          8d
kube-flannel-ds-amd64-w6f9h          1/1     Running   4          8d
kube-proxy-77pbc                     1/1     Running   3          8d
kube-proxy-qs655                     1/1     Running   3          8d
kube-proxy-xffq4                     1/1     Running   0          8d
kube-scheduler-k8s-master            1/1     Running   0          8d

[ik8s@k8s-master ~]$ kubectl delete pods/pod-sa-demo    #在進行刪除pod測試時,仍是會報Forbidden,這是由於在受權時就沒授予delete權限的。
Error from server (Forbidden): pods "pod-sa-demo" is forbidden: User "kube-user1" cannot delete resource "pods" in API group "" in the namespace "default"

從上面的操做能夠看出,clusterrole的定義和clusterrolebinding的綁定,能夠獲取到集羣內全部資源的對應權限。

User --> Rolebinding --> Clusterrole

將用戶kube-user1經過角色綁定(RoleBinding)到集羣角色cluster-reader當中,此時kube-user1僅做用於當前名稱空間的全部pods資源的權限。

1)綁定

#首先刪除上面的clusterrolebinding
[root@k8s-master manfests]# kubectl delete clusterrolebinding kube-user1-read-all-pods
clusterrolebinding.rbac.authorization.k8s.io "kube-user1-read-all-pods" deleted

[root@k8s-master manfests]# kubectl create rolebinding kube-user1-read-pods --clusterrole=cluster-reader --user=kube-user1 --dry-run -o yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  creationTimestamp: null
  name: kube-user1-read-pods
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-reader
subjects:
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: kube-user1
  
[root@k8s-master manfests]# kubectl create rolebinding kube-user1-read-pods --clusterrole=cluster-reader --user=kube-user1 --dry-run -o yaml > rolebinding-clusterrole-demo.yaml
[root@k8s-master manfests]# vim rolebinding-clusterrole-demo.yaml    #編輯資源清單文件
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: kube-user1-read-pods
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-reader
subjects:
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: kube-user1
  
[root@k8s-master manfests]# kubectl apply -f rolebinding-clusterrole-demo.yaml 
rolebinding.rbac.authorization.k8s.io/kube-user1-read-pods created
[root@k8s-master manfests]# kubectl get rolebinding kube-user1-read-pods 
NAME                   AGE
kube-user1-read-pods   32s
[root@k8s-master manfests]# kubectl describe rolebinding kube-user1-read-pods
Name:         kube-user1-read-pods
Labels:       <none>
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"rbac.authorization.k8s.io/v1","kind":"RoleBinding","metadata":{"annotations":{},"name":"kube-user1-read-pods","namespace":"...
Role:
  Kind:  ClusterRole
  Name:  cluster-reader
Subjects:
  Kind  Name        Namespace
  ----  ----        ---------
  User  kube-user1 

2)權限測試

[ik8s@k8s-master ~]$ kubectl get pods 
NAME                  READY   STATUS    RESTARTS   AGE
nginx-statefulset-0   1/1     Running   0          3d1h
nginx-statefulset-1   1/1     Running   0          3d1h
nginx-statefulset-2   1/1     Running   0          3d1h
nginx-statefulset-3   1/1     Running   0          3d1h
pod-sa-demo           1/1     Running   0          28h

[ik8s@k8s-master ~]$ kubectl get pods -n kube-system
Error from server (Forbidden): pods is forbidden: User "kube-user1" cannot list resource "pods" in API group "" in the namespace "kube-system"

從上面的操做能夠看出,角色綁定(Rolebinding)和集羣角色(ClusterRole)綁定後,用戶只擁有本身當前名稱空間的對應的權限。

相關文章
相關標籤/搜索