Ray Lee | 李宗叡
Learn or Die
Published in
5 min readDec 28, 2020

--

Photo by Austin Distel on Unsplash

# 目標

  • 在 cluster 內建立一個 user, 該 user 只可通過 client 端的 private key 以及 certificate 方可存取
  • 限制 cluster 內特定 user 只可存取特定的 namespace
  • 在本文中, 我們會建立一個 user ray, group learnordie, 只可訪問 namespace kube-system

# 建立用戶憑證

# 建立一個 private key, 名稱為 ray.key

openssl genrsa -out ray.key 2048

# 建立一個 csr, 並定義 user name 以及 user group

openssl req -new -key ray.key -out ray.csr -subj "/CN=ray/O=learnordie"

# 生成最終 crt 文件

預設 Kubernetes CA 文件位置為 /etc/kubernetes/pki/ 目錄下

openssl x509 -req -in ray.csr -CA /etc/kubernetes/pki/ca.crt -CAkey /etc/kubernetes/pki/ca.key -CAcreateserial -out ray.crt -days 500

# 建立 user 及 context

上面我們生成了由 Kubernetes CA 所簽署的 crt, 接下來我們使用這個 crt 來建立 user, 以及 context

# 建立 user

kubectl config set-credentials ray --client-certificate=ray.crt  --client-key=ray.key

# 建立 context

可以擁有多個 context, 用於記住不同操作對象的整套資訊, 例如 user ray, cluster 為 ray-cluster, 預設的 namespace 為 ray-namespace, 可使用 kubectl config use-context 來設定預設的 context, 可使用 kubectl config current-context 取得預設 context

kubectl config set-context demo-context --cluster=yourClusterName --namespace=kube-system --user=ray

# 建立 role 以及 rolebinding

依照上面的步驟, 已經建立了 user 以及 context, 這時如果我們使用此 context 來取得資訊, 將會出錯, 因為此時的 user ray 並沒有任何的權限

kubectl get pods --context demo-context

因此, 接下來我們要建立代表權限的 role, 以及用來綁定 user 以及 role 的 role binding

# 建立 role

建立以下 yaml file, 名為 demo-role.yaml

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: demo-role
namespace: kube-system
rules:
- apiGroups: ["", "apps"]
resources: ["pods", "replicasets", "deployments"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]

demo-role.yaml 建立該 role

kubectl apply -f demo-role.yaml

# 建立 role binding

建立以下 yaml file, 名為 demo-role-binding.yaml

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: demo-rolebinding
namespace: kube-system
subjects:
- kind: User
name: ray
apiGroup: ""
roleRef:
kind: Role
name: demo-role
apiGroup: ""

demo-role-binding.yaml 建立該 role binding

kubectl apply -f demo-role-binding.yaml

這時如果可以看看 role 以及 role binding 有沒有出現在 kube-system

kubectl get role -n kube-system
kubectl get rolebinding -n kube-system

# 驗證

沒意外的話, 現在使用 demo-context 來取得 namespace 為 kube-system 的 resources pods, deployments, replicasets 都是沒有問題的

kubectl get pods --context demo-context

每次使用 demo-context, Kubernetes 都會去檢查當初簽署的 ray.csr 以及 ray.crt, 換言之, 要是少了這兩樣東西, 便無法以 ray 這個 user 對 cluster 做操作, 若要變更檢查金鑰的目錄, 可修改 config 檔案, 預設位置為 ~/.kube/config

# 參考來源

官方文件

官方文件

官方文件

man openssl

--

--

Ray Lee | 李宗叡
Learn or Die

It's Ray. I do both backend and frontend, but more focus on backend. I like coding, and would like to see the whole picture of a product.