Triển khai OPA Gatekeeper trên Kubernetes Cluster
Chúng ta sẽ cài đặt OPA Gatekeeper thông qua Helm chart để quản lý chính sách tuân thủ trong cluster. Đây là bước nền tảng để hệ thống AI Governance bắt đầu hoạt động.
Tại sao cần Helm chart? Nó đóng gói cấu hình phức tạp của Gatekeeper (bao gồm controller, webhook, và các resource cần thiết) thành một gói cài đặt đơn giản, đồng thời cho phép tùy chỉnh sâu thông qua file values.yaml.
Kết quả mong đợi: Namespace 'gatekeeper-system' được tạo, các pod của Gatekeeper chạy ở trạng thái 'Running', và webhook được đăng ký thành công.
Đầu tiên, thêm repository Helm của OPA Gatekeeper vào hệ thống của bạn.
helm repo add gatekeeper https://open-policy-agent.github.io/gatekeeper/charts
helm repo update
Kiểm tra version mới nhất của chart để đảm bảo tính tương thích.
helm search repo gatekeeper --versions
Tạo file cấu hình tùy chỉnh values.yaml để tăng tốc độ khởi tạo và kích hoạt logging chi tiết cho việc debug sau này.
Đường dẫn: /tmp/gatekeeper-values.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: gatekeeper-config
namespace: gatekeeper-system
data:
sync-k8s-objects: "true"
audit-sync-only: "false"
exclude-namespace-names: ""
exclude-group-kinds: ""
exclude-resource-names: ""
audit-interval-seconds: "60"
---
# Cấu hình Helm values
controller:
replicas: 2
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "500m"
memory: "512Mi"
extraArgs:
- --log-level=debug
mutating-webhook:
replicas: 2
resources:
requests:
cpu: "50m"
memory: "64Mi"
limits:
cpu: "250m"
memory: "256Mi"
validating-webhook:
replicas: 2
resources:
requests:
cpu: "50m"
memory: "64Mi"
limits:
cpu: "250m"
memory: "256Mi"
cert-manager:
enabled: true
replicas: 1
Cài đặt Gatekeeper với file values.yaml vừa tạo vào namespace gatekeeper-system.
helm install gatekeeper gatekeeper/gatekeeper-crds --namespace gatekeeper-system --create-namespace -f /tmp/gatekeeper-values.yaml
Chờ vài giây để các pod khởi động và xác minh trạng thái.
kubectl get pods -n gatekeeper-system -l app=gatekeeper
Verify kết quả: Bạn phải thấy các pod như 'gatekeeper-audit', 'gatekeeper-controller', 'gatekeeper-webhook' đang ở trạng thái 'Running' (1/1 READY). Nếu có pod ở trạng thái 'CrashLoopBackOff', hãy kiểm tra log bằng lệnh kubectl logs -n gatekeeper-system .
Cấu trúc và cú pháp cơ bản của Rego
Trước khi viết chính sách, cần hiểu Rego là ngôn ngữ logic declarative dùng để định nghĩa các quy tắc trong OPA. Rego hoạt động trên cơ sở 'fact' (dữ liệu đầu vào) và 'rule' (logic xử lý).
Tại sao cần hiểu Rego? Chính sách AI Governance sẽ được viết bằng Rego. Nếu không nắm vững cú pháp, bạn sẽ không thể viết được các quy tắc phức tạp như kiểm tra phiên bản model hay audit trail.
Kết quả mong đợi: Bạn hiểu được cách một file .rego hoạt động, từ phần import, define data, đến phần rule kiểm tra và return kết quả.
Một file Rego tiêu chuẩn gồm 3 phần chính: Import (nhập thư viện), Default/Rule (định nghĩa logic), và Output (kết quả trả về). Cấu trúc này áp dụng cho cả ConstraintTemplate.
Đường dẫn: /tmp/example-policy.rego (file mẫu để học)
package k8spublic
# Import thư viện Kubernetes
import data.kubernetes
# Rule: Kiểm tra nếu container sử dụng image "nginx" thì bị từ chối
violation[{"msg": msg}] {
container := input.review.object.spec.containers[_]
container.image == "nginx"
msg := sprintf("Container %v is not allowed to use nginx image", [container.name])
}
Trong file trên, 'violation' là rule bắt buộc phải có trong OPA Gatekeeper. Nếu rule này trả về một mảng không rỗng, Gatekeeper sẽ từ chối request. Biến 'input.review.object' chứa manifest của resource đang được submit (Pod, Deployment, v.v.).
Viết chính sách kiểm tra phiên bản AI Model
Bây giờ chúng ta sẽ viết chính sách thực tế: Chỉ cho phép triển khai Pod nếu AI Model được chỉ định trong annotation đã qua audit (audit status = "approved").
Tại sao cần chính sách này? Trong môi trường AI, việc deploy model chưa qua audit có thể gây ra rủi ro về bias, security vulnerability, hoặc compliance violation. Chúng ta cần chặn cứng ở mức độ Kubernetes.
Kết quả mong đợi: Một file ConstraintTemplate với logic Rego hoàn chỉnh, kiểm tra annotation 'ai-model-audit-status' trên Pod.
Chúng ta sẽ tạo file ConstraintTemplate định nghĩa logic Rego. File này đóng vai trò như một "mẫu" chính sách.
Đường dẫn: /tmp/ai-model-audit-template.yaml
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8saimodelaudit
annotations:
description: "Enforce AI Model Audit Status before deployment."
spec:
crd:
spec:
names:
kind: K8sAIModelAudit
validation:
openAPIV3Schema:
type: object
properties:
allowedStatus:
type: string
description: "Required audit status (e.g., 'approved')"
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8saimodelaudit
import data.kubernetes
# Rule: Kiểm tra Pod
violation[{
"msg": msg
}] {
container := input.review.object.spec.containers[_]
not is_approved(container)
msg := sprintf("Container %v uses an AI model that has not been audited or is not approved.", [container.name])
}
# Helper function: Kiểm tra trạng thái audit
is_approved(container) {
status := input.review.object.metadata.annotations["ai-model-audit-status"]
status == "approved"
}
# Fallback: Nếu không có annotation, coi là chưa approved
is_approved(container) {
not input.review.object.metadata.annotations["ai-model-audit-status"]
}
# Nếu container không dùng AI model (không có annotation), cho phép
is_approved(container) {
not input.review.object.metadata.annotations["ai-model-audit-status"]
not container.image =~ ".*ai-model.*"
}
Logic ở trên hoạt động như sau: Nó duyệt qua từng container trong Pod. Nếu container có image chứa từ "ai-model" hoặc có annotation "ai-model-audit-status", nó sẽ kiểm tra xem giá trị annotation có phải là "approved" không. Nếu không, nó trả về một rule 'violation' để chặn request.
Triển khai chính sách vào Cluster
Sau khi có ConstraintTemplate, chúng ta cần tạo một Constraint cụ thể để áp dụng chính sách đó vào cluster. ConstraintTemplate là "lớp", còn Constraint là "đối tượng" cụ thể.
Tại sao cần tách biệt? ConstraintTemplate định nghĩa logic (Rego), còn Constraint định nghĩa tham số cụ thể (ví dụ: status yêu cầu là gì, áp dụng cho namespace nào). Điều này giúp tái sử dụng logic cho nhiều chính sách khác nhau.
Kết quả mong đợi: ConstraintTemplate và Constraint được tạo thành công, và Gatekeeper bắt đầu áp dụng chính sách lên các request mới.
Đầu tiên, áp dụng file ConstraintTemplate đã viết vào cluster.
kubectl apply -f /tmp/ai-model-audit-template.yaml
Verify rằng ConstraintTemplate đã được tạo.
kubectl get constrainttemplate k8saimodelaudit
Tiếp theo, tạo file Constraint để kích hoạt chính sách với tham số 'allowedStatus' là 'approved'. File này sẽ áp dụng cho toàn bộ cluster.
Đường dẫn: /tmp/ai-model-audit-constraint.yaml
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sAIModelAudit
metadata:
name: enforce-ai-model-audit
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
parameters:
allowedStatus: "approved"
Áp dụng file Constraint vào cluster.
kubectl apply -f /tmp/ai-model-audit-constraint.yaml
Verify rằng Constraint đã được tạo và Gatekeeper đã nhận diện nó.
kubectl get constraint enforce-ai-model-audit
Để chắc chắn chính sách đang hoạt động, kiểm tra trạng thái enforcement của Gatekeeper.
kubectl get constraints -A
Verify kết quả: Bạn phải thấy constraint 'enforce-ai-model-audit' trong danh sách. Nếu có, Gatekeeper đã sẵn sàng chặn các Pod không tuân thủ.
Kiểm tra và xác minh hoạt động của chính sách
Bước cuối cùng là thực hiện thử nghiệm deploy Pod để xác minh chính sách có chặn đúng hay không. Chúng ta sẽ thử 2 trường hợp: một Pod hợp lệ (có annotation approved) và một Pod không hợp lệ (thiếu annotation).
Tại sao cần test? Code có thể đúng cú pháp nhưng logic có thể sai trong thực tế. Test trực tiếp trên cluster là cách duy nhất để đảm bảo AI Governance hoạt động như mong đợi.
Kết quả mong đợi: Pod có annotation 'approved' được tạo thành công. Pod không có annotation (hoặc có status khác) bị từ chối với lỗi rõ ràng từ Gatekeeper.
Trường hợp 1: Deploy Pod HỢP LỆ (có annotation audit-status: approved).
Đường dẫn: /tmp/test-pod-approved.yaml
apiVersion: v1
kind: Pod
metadata:
name: test-pod-approved
annotations:
ai-model-audit-status: "approved"
spec:
containers:
- name: ai-inference
image: my-registry/ai-model:v1.2.3-secure
ports:
- containerPort: 80
Áp dụng Pod hợp lệ.
kubectl apply -f /tmp/test-pod-approved.yaml
Kiểm tra trạng thái Pod.
kubectl get pod test-pod-approved
Verify kết hợp: Pod phải chuyển sang trạng thái 'Running' hoặc 'Pending' (nếu thiếu resource), nhưng KHÔNG có lỗi từ Admission Control. Lệnh apply trả về "pod/test-pod-approved created".
Trường hợp 2: Deploy Pod KHÔNG HỢP LỆ (thiếu annotation hoặc status sai).
Đường dẫn: /tmp/test-pod-rejected.yaml
apiVersion: v1
kind: Pod
metadata:
name: test-pod-rejected
# Không có annotation ai-model-audit-status
spec:
containers:
- name: ai-inference-unsafe
image: my-registry/ai-model:v1.2.3-unsafe
ports:
- containerPort: 80
Thử áp dụng Pod không hợp lệ.
kubectl apply -f /tmp/test-pod-rejected.yaml
Quan sát lỗi trả về. Bạn sẽ thấy thông báo lỗi từ Gatekeeper.
kubectl describe pod test-pod-rejected 2>&1 | grep -A 5 "Events"
Verify kết quả: Lệnh apply phải FAIL với thông báo tương tự: "admission webhook 'validation.gatekeeper.sh' denied the request: Container ai-inference-unsafe uses an AI model that has not been audited or is not approved." Pod test-pod-rejected sẽ không xuất hiện trong danh sách kubectl get pods (trạng thái Pending do bị chặn).
Xóa các Pod test để dọn dẹp môi trường.
kubectl delete pod test-pod-approved test-pod-rejected --ignore-not-found=true
Điều hướng series:
Mục lục: Series: Xây dựng nền tảng AI Governance tự động với OPA, Prometheus và Policy Engine
« Phần 1: Chuẩn bị môi trường và kiến trúc tổng quan cho AI Governance
Phần 3: Cấu hình Prometheus để thu thập và giám sát chỉ số AI »