Kubernetes Cluster 中 API Server 是管理整個叢集的大腦, API-Server 一般執行在 Controller Plane (Master Node)上,維運人員通常會透過 CLI kubectl 工具去管理 Kubernetes。
但還有許多方式可以存取 Kubernetes API Server ,今天會建立一個特殊場景。有一個名為 Jean 的使用者,透過 Rest API 的方式存取 Kubernetes 的資源
向 Kubernetes API Server 發起請求通常需要有一個有權限的 ServiceAccount ,使用這個 ServiceAccount 通過 ClusterRole 、 Role 、 ClusterRoleBinding 、 RoleBinding 賦予操作相關資源的權限, 與 API Server 的請求基本上是基於 TLS ,所以 User 發起請求的時候還需要自帶憑證,當然我們也可以透過非安全方式存取 API Server , 但是不推薦在環境中使用,這邊就不再多做說明。
kubectl get svc kubernetes -o go-template --template='{{.spec.clusterIP}}'10.96.0.1
第一種就是直接確認 master Node 的 IP ,第二種是可以透過 Kubernetes Service 上的 VIP 。
access pods list
例如我們可以透過 curl 指令直接存取 Master Node IP 上的 API Server
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
curl https://172.18.0.5:6443/api/v1/namespaces/default/pods/ --cacert /etc/kubernetes/pki/ca.crt --cert ./jean.crt --key ./jean.key
{"kind": "Status",
"apiVersion": "v1",
"metadata": {},
"status": "Failure",
"message": "pods is forbidden: User \"jean\" cannot list resource \"pods\" in API group \"\" in the namespace \"default\"",
"reason": "Forbidden",
"details": {"kind": "pods"},
"code": 403}
但這裡會發現無法存取 Pod resource in "" group 這邊是因為沒有針對 jean 去設定 RBAC 的存取範圍。
新增一個讀取 default namespace 的 role
1
2
3
4
5
6
7
8
9
apiVersion:rbac.authorization.k8s.io/v1kind:Rolemetadata:namespace:defaultname:pod-readerrules:- apiGroups:[""]# "" indicates the core API groupresources:["pods"]verbs:["get","watch","list"]
幫 Jean 綁定有能力讀取 Pod 的角色
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
apiVersion:rbac.authorization.k8s.io/v1# This role binding allows "jean" to read pods in the "default" namespace.# You need to already have a Role named "pod-reader" in that namespace.kind:RoleBindingmetadata:name:read-podsnamespace:defaultsubjects:# You can specify more than one "subject"- kind:Username:jane# "name" is case sensitiveapiGroup:rbac.authorization.k8s.ioroleRef:# "roleRef" specifies the binding to a Role / ClusterRolekind:Role#this must be Role or ClusterRolename:pod-reader# this must match the name of the Role or ClusterRole you wish to bind toapiGroup:rbac.authorization.k8s.io
完成以上綁定的動作之後 Jean 就有了讀取 default namespaces 的權限了
reaccess kubernetes api server
一樣透過 curl 指令存取 Kubernetes api server ,最後透過 jq 幫忙整理輸出的內容。