# OPA Gatekeeper 實作 ## 什麼是 Open Policy Agent (OPA)? 和 OPA Gatekeeper 有什麼差別? 在開發服務的時候,我們會需要注意到服務的 驗證 (Authentication) 和 授權 (Authorization) 這兩套機制要怎麼實作,區別如下: * Authentication(驗證):確認使用者是否存在於系統當中,比方你在登入公司系統,系統會先確認你是否是這家公司的員工。 * Authorization(授權):根據使用者的角色來授予應有的權限,成功登入公司系統後,系統會根據你的職等,決定你可以看什麼資料、做什麼事情。 而 OPA 的概念就是要 把 授權(Authorization) 的概念從服務中獨立出來,讓不同的服務都能夠呼叫同一個 OPA Server 做 授權 (Authorization) 這件事,概念圖如下: ![image](https://hackmd.io/_uploads/rkPnM16w1e.png) 比方說 API Server 接收到了一個 Request,在已經確認這個 Request 是由合法的使用者發出的請求後,API Server 會再發出一個請求到 OPA Server,確認這個 Request 要做的事情和不合乎規範,若合乎系統規範,回傳成功,反之則回傳失敗。 那 OPA Gatekeeper 又是什麼? Gatekeeper 是專為 OPA 的 Kubernetes Admission Control 使用個案所建立。OPA Gatekeeper 封裝了 OPA 的程式碼,讓 OPA 可以以 Webhook Server 的方式運作在 Kubernetes 裡面,解決了 Kubernetes 各種部署的審核問題。 ## 1. 安裝 ``` $ kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/v3.18.2/deploy/gatekeeper.yaml ``` ## 2. 建立 replicalimits 的 ConstraintTemplate * ConstraintTemplate 定義了用於強制執行約束的政策,以及約束的一般模式。 ``` $ kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper-library/master/library/general/replicalimits/template.yaml ``` ``` $ kubectl -n gatekeeper-system get constrainttemplate NAME AGE k8sreplicalimits 13s ``` ## 3. 設定 Deployment Replica 數量只能在 3 到 5 之間 ``` $ cat <<EOF | kubectl apply -f - apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sReplicaLimits metadata: name: replica-limits spec: match: kinds: - apiGroups: ["apps"] kinds: ["Deployment"] - apiGroups: ["autoscaling"] kinds: ["Scale"] parameters: ranges: - min_replicas: 3 max_replicas: 5 EOF ``` ``` $ kubectl -n gatekeeper-system get k8sreplicalimits NAME ENFORCEMENT-ACTION TOTAL-VIOLATIONS replica-limits deny ``` ## 建立 6 個 replicas 的 deployment ``` $ kubectl create deployment nginx --image=nginx --replicas=6 error: failed to create deployment: admission webhook "validation.gatekeeper.sh" denied the request: [replica-limits] The provided number of replicas is not allowed for Deployment: nginx. Allowed ranges: {"ranges": [{"max_replicas": 5, "min_replicas": 3}]} ``` ## 建立 deployment 後也無法被 scale 超過 5 個 pod ``` $ kubectl create deployment nginx --image=nginx --replicas=5 $ kubectl scale deploy nginx --replicas=999 Error from server (Forbidden): admission webhook "validation.gatekeeper.sh" denied the request: [replica-limits] The provided number of replicas is not allowed for Scale: nginx. Allowed ranges: {"ranges": [{"max_replicas": 5, "min_replicas": 3}]} ``` ## 參考 https://open-policy-agent.github.io/gatekeeper/website/docs/install https://hackmd.io/@QI-AN/OPA-Gatekeeper