antony@notes:~/kubernetes$ cat "OPA-Gatekeeper-for-Kubernetes-Admission-Control.md"
OPA Gatekeeper for Kubernetes Admission Control
OPA Gatekeeper for Kubernetes Admission Control
甚麼是 Open Policy Agent (OPA)? 和 OPA Gatekeeper 有什麼差別?
在開發服務的時候,我們會需要注意到服務的 驗證 (Authentication) 和 授權 (Authorization) 這兩套機制要怎麼實作,區別如下:
- Authentication(驗證):確認使用者是否存在於系統當中,比方你在登入公司系統,系統會先確認你是否是這家公司的員工。
- Authorization(授權):根據使用者的角色來授予應有的權限,成功登入公司系統後,系統會根據你的職等,決定你可以看什麼資料、做什麼事情。
而 OPA 的概念就是要 把 授權(Authorization) 的概念從服務中獨立出來,讓不同的服務都能夠呼叫同一個 OPA Server 做 授權 (Authorization) 這件事,概念圖如下:

比方說 API Server 接收到了一個 Request,在已經確認這個 Request 是由合法的使用者發出的請求後,API Server 會再發出一個請求到 OPA Server,確認這個 Request 要做的事情和不合乎規範,若合乎系統規範,回傳成功,反之則回傳失敗。
那 OPA Gatekeeper 又是什麼? Gatekeeper 是專為 OPA 的 Kubernetes Admission Control 使用個案所建立。OPA Gatekeeper 封裝了 OPA 的程式碼,讓 OPA 可以以 Webhook Server 的方式運作在 Kubernetes 裡面,解決了 Kubernetes 各種部署的審核問題。
開始實作
目標 : 限制 Deployment 的 Replicas 數量
# 1. 安裝 OPA Gatekeeper
$ 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
# 3. 設定 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"]
# 以下為限制 kubectl scale 的時候也會阻擋,如果不設定,就只有 Create 的時候會阻擋
- apiGroups: ["autoscaling"] # add
kinds: ["Scale"] # add
parameters:
ranges:
- min_replicas: 3
max_replicas: 5
EOF
# 4. 建立 test namespace
$ kubectl create ns test
namespace/test created
# 5. 建立 6 個 replicas 的 deployment
$ kubectl -n test 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}]}
# 6. 建立符合規則的 deployment
$ kubectl -n test create deployment nginx --image=nginx --replicas=5
# 7. 檢視 pod 運作狀態
$ kubectl -n test get pod
NAME READY STATUS RESTARTS AGE
nginx-676b6c5bbc-crdj5 1/1 Running 0 5m50s
nginx-676b6c5bbc-j6dlq 1/1 Running 0 5m50s
nginx-676b6c5bbc-r42nr 1/1 Running 0 5m50s
nginx-676b6c5bbc-wkbtw 1/1 Running 0 5m50s
nginx-676b6c5bbc-z54w5 1/1 Running 0 5m50s
# 8. 測試將 nginx deployment 的 replica scale 到 999
$ kubectl -n test scale deployment nginx --replicas 999 --dry-run=server
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}]}
# 成功阻擋,收工!