OPA Gatekeeper GreenOps
OPA Gatekeeper GreenOps Sustainability Policy Kubernetes Admission Controller Rego ConstraintTemplate Resource Limits Carbon Tracking
| Policy | Purpose | Green Impact | Enforcement |
|---|---|---|---|
| Resource Limits Required | ทุก Container ต้องมี Limits | ลด Over-provisioning | Deny |
| Max CPU/Memory | จำกัด Resource ต่อ Pod | ป้องกันใช้เกิน | Deny |
| Image Size Limit | จำกัดขนาด Image | ลด Storage, Pull Time | Deny |
| Namespace Quota | ทุก NS ต้องมี Quota | จำกัด Resource ทั้ง NS | Deny |
| Idle Pod Alert | ตรวจ Pod ที่ไม่ใช้งาน | ลบ Pod ที่ไม่จำเป็น | Audit |
| ARM Node Preference | ให้ใช้ ARM Node ก่อน | ลดพลังงาน 30-40% | Warn |
Policy Implementation
# === OPA Gatekeeper GreenOps Policies ===
# ConstraintTemplate: Require Resource Limits
# apiVersion: templates.gatekeeper.sh/v1
# kind: ConstraintTemplate
# metadata:
# name: k8srequiredresourcelimits
# spec:
# crd:
# spec:
# names:
# kind: K8sRequiredResourceLimits
# validation:
# openAPIV3Schema:
# type: object
# properties:
# maxCPU:
# type: string
# maxMemory:
# type: string
# targets:
# - target: admission.k8s.gatekeeper.sh
# rego: |
# package k8srequiredresourcelimits
# violation[{"msg": msg}] {
# container := input.review.object.spec.containers[_]
# not container.resources.limits
# msg := sprintf("Container '%v' must have resource limits", [container.name])
# }
# violation[{"msg": msg}] {
# container := input.review.object.spec.containers[_]
# cpu := container.resources.limits.cpu
# max_cpu := input.parameters.maxCPU
# cpu > max_cpu
# msg := sprintf("Container '%v' CPU limit %v exceeds max %v", [container.name, cpu, max_cpu])
# }
# Constraint: Apply to production namespace
# apiVersion: constraints.gatekeeper.sh/v1beta1
# kind: K8sRequiredResourceLimits
# metadata:
# name: require-limits-production
# spec:
# enforcementAction: deny
# match:
# kinds:
# - apiGroups: [""]
# kinds: ["Pod"]
# - apiGroups: ["apps"]
# kinds: ["Deployment", "StatefulSet"]
# namespaces: ["production", "staging"]
# parameters:
# maxCPU: "2"
# maxMemory: "4Gi"
from dataclasses import dataclass
@dataclass
class GreenOpsPolicy:
name: str
rego_check: str
parameters: str
enforcement: str
green_impact: str
policies = [
GreenOpsPolicy("Require Resource Limits",
"not container.resources.limits → violation",
"maxCPU: 2, maxMemory: 4Gi",
"deny (production), warn (dev)",
"ลด Over-provisioning 30-50%"),
GreenOpsPolicy("Require Resource Requests",
"not container.resources.requests → violation",
"minCPU: 100m, minMemory: 128Mi",
"deny",
"Scheduler จัดวาง Pod ได้ดีขึ้น"),
GreenOpsPolicy("Image Size Limit",
"image_size > maxSize → violation",
"maxSize: 500MB",
"deny (production), audit (dev)",
"ลด Storage 40-60%, Pull Time ลด"),
GreenOpsPolicy("No Latest Tag",
"container.image endsWith ':latest' → violation",
"-",
"deny",
"ป้องกัน Unexpected Image Change"),
GreenOpsPolicy("Namespace ResourceQuota",
"not exists ResourceQuota in NS → violation",
"requiredQuotas: [cpu, memory, pods]",
"deny",
"จำกัด Resource ทั้ง Namespace"),
GreenOpsPolicy("Prefer ARM Nodes",
"not nodeSelector['arch'] == 'arm64' → warn",
"-",
"warn (แนะนำ ไม่บังคับ)",
"ARM ใช้พลังงานน้อยกว่า x86 30-40%"),
]
print("=== GreenOps Policies ===")
for p in policies:
print(f"\n [{p.name}]")
print(f" Check: {p.rego_check}")
print(f" Params: {p.parameters}")
print(f" Enforce: {p.enforcement}")
print(f" Impact: {p.green_impact}")
Deployment & Testing
# === Gatekeeper Deployment & Policy Testing ===
# Install Gatekeeper
# helm repo add gatekeeper https://open-policy-agent.github.io/gatekeeper/charts
# helm install gatekeeper gatekeeper/gatekeeper \
# --namespace gatekeeper-system \
# --create-namespace \
# --set replicas=3 \
# --set audit.replicas=1 \
# --set audit.interval=60
# Test Policy - This should be REJECTED
# kubectl apply -f - <
Sustainability Metrics
# === GreenOps Metrics Dashboard ===
@dataclass
class GreenMetric:
metric: str
formula: str
target: str
dashboard: str
metrics = [
GreenMetric("Resource Efficiency",
"Actual CPU Used / CPU Requested × 100",
"60-80% (ไม่ Over-provision)",
"Prometheus: container_cpu_usage / kube_pod_resource_request"),
GreenMetric("Policy Compliance Rate",
"Passed Resources / Total Resources × 100",
"> 95% (production), > 80% (dev)",
"Gatekeeper Audit Status → Grafana"),
GreenMetric("Over-provisioning Rate",
"Resources where Request > 2× Used / Total",
"< 10%",
"VPA Recommendations → Dashboard"),
GreenMetric("Watt per Pod",
"Node Power / Pod Count",
"ลด 10% ต่อ Quarter",
"Kepler (Kubernetes Energy Metrics)"),
GreenMetric("CO2 per Namespace",
"Namespace kWh × Carbon Factor",
"ลด 15% ต่อปี",
"Kepler + Cloud Carbon Footprint"),
GreenMetric("Image Size Average",
"Sum(Image Size) / Image Count",
"< 200MB Average",
"Container Registry Metrics"),
]
print("=== GreenOps Metrics ===")
for m in metrics:
print(f" [{m.metric}]")
print(f" Formula: {m.formula}")
print(f" Target: {m.target}")
print(f" Dashboard: {m.dashboard}")
เคล็ดลับ
- Audit First: เริ่ม Audit Mode ก่อน Deny ดู Violation ก่อน Enforce
- VPA: ใช้ Vertical Pod Autoscaler แนะนำ Resource ที่เหมาะสม
- Kepler: ใช้ Kepler วัดพลังงานต่อ Pod ได้แม่นยำ
- ARM: ใช้ Policy แนะนำ ARM Node ลดพลังงาน 30-40%
- Image: บังคับ Distroless/Alpine ลดขนาด Image 60-80%
การดูแลระบบในสภาพแวดล้อม Production
การบริหารจัดการระบบ Production ที่ดีต้องมี Monitoring ครอบคลุม ใช้เครื่องมืออย่าง Prometheus + Grafana สำหรับ Metrics Collection และ Dashboard หรือ ELK Stack สำหรับ Log Management ตั้ง Alert ให้แจ้งเตือนเมื่อ CPU เกิน 80% RAM ใกล้เต็ม หรือ Disk Usage สูง
Backup Strategy ต้องวางแผนให้ดี ใช้หลัก 3-2-1 คือ มี Backup อย่างน้อย 3 ชุด เก็บใน Storage 2 ประเภทต่างกัน และ 1 ชุดต้องอยู่ Off-site ทดสอบ Restore Backup เป็นประจำ อย่างน้อยเดือนละครั้ง เพราะ Backup ที่ Restore ไม่ได้ก็เหมือนไม่มี Backup
เรื่อง Security Hardening ต้องทำตั้งแต่เริ่มต้น ปิด Port ที่ไม่จำเป็น ใช้ SSH Key แทน Password ตั้ง Fail2ban ป้องกัน Brute Force อัพเดท Security Patch สม่ำเสมอ และทำ Vulnerability Scanning อย่างน้อยเดือนละครั้ง ใช้หลัก Principle of Least Privilege ให้สิทธิ์น้อยที่สุดที่จำเป็น
OPA Gatekeeper คืออะไร
Policy Engine Rego Kubernetes Admission Controller ConstraintTemplate Constraint Webhook Reject Security Compliance Cost GreenOps
GreenOps Policy มีอะไร
Resource Limits Max CPU Memory Image Size Namespace Quota Idle Detection ARM Preference Distroless Alpine Over-provisioning Right-sizing
เขียน Policy อย่างไร
ConstraintTemplate Rego violation msg Constraint Parameters Match Namespace kinds Dry-run Audit Deny Apply kubectl Test Reject Allow
วัดผล GreenOps อย่างไร
Resource Efficiency 60-80% Compliance Rate Watt/Pod CO2/Namespace Over-provisioning Image Size Prometheus Grafana Kepler VPA Dashboard Alert
สรุป
OPA Gatekeeper GreenOps Rego Policy Resource Limits Image Size Namespace Quota ARM Kepler CO2 Prometheus Grafana Audit Deny Production
