writing-skills
writing-skills
Use when creating new skills, editing existing skills, or verifying skills work before deployment
enforce-policy-as-codeImplement policy-as-code enforcement using OPA Gatekeeper or Kyverno to validate and mutate Kubernetes resources according to organizational policies. Covers constraint templates, admission control, audit mode, reporting violations, and integrating with CI/CD pipelines for shift-left policy validation. Use when enforcing resource configuration standards, pr…
Independent GitHub snapshot · Automated classification · Original documentation governs
用 OPA Gatekeeper 或 Kyverno 行宣告式策,驗與變 Kubernetes 資源。
見 Extended Examples 備全設與模。
布 OPA Gatekeeper 或 Kyverno 為入控器。
OPA Gatekeeper:
# Install Gatekeeper using Helm
helm repo add gatekeeper https://open-policy-agent.github.io/gatekeeper/charts
helm repo update
# Install with audit enabled
helm install gatekeeper gatekeeper/gatekeeper \
--namespace gatekeeper-system \
--create-namespace \
--set audit.replicas=2 \
--set replicas=3 \
--set validatingWebhookFailurePolicy=Fail \
--set auditInterval=60
# Verify installation
kubectl get pods -n gatekeeper-system
kubectl get crd | grep gatekeeper
# Check webhook configuration
kubectl get validatingwebhookconfigurations gatekeeper-validating-webhook-configuration -o yaml
Kyverno:
# Install Kyverno using Helm
helm repo add kyverno https://kyverno.github.io/kyverno/
helm repo update
# Install with HA setup
helm install kyverno kyverno/kyverno \
--namespace kyverno \
--create-namespace \
--set replicaCount=3 \
--set admissionController.replicas=3 \
--set backgroundController.replicas=2 \
--set cleanupController.replicas=2
# Verify installation
kubectl get pods -n kyverno
kubectl get crd | grep kyverno
# Check webhook configurations
kubectl get validatingwebhookconfigurations kyverno-resource-validating-webhook-cfg
kubectl get mutatingwebhookconfigurations kyverno-resource-mutating-webhook-cfg
設名空排除:
# gatekeeper-config.yaml
apiVersion: config.gatekeeper.sh/v1alpha1
kind: Config
metadata:
name: config
namespace: gatekeeper-system
spec:
match:
- excludedNamespaces:
- kube-system
- kube-public
- kube-node-lease
- gatekeeper-system
processes:
- audit
- webhook
validation:
traces:
- user: system:serviceaccount:gatekeeper-system:gatekeeper-admin
kind:
group: ""
version: v1
kind: Namespace
得:策引艙多副運。CRD 已裝(Gatekeeper 之 ConstraintTemplate、Constraint;Kyverno 之 ClusterPolicy、Policy)。驗/變鈎活。審控運。
敗:
kubectl logs -n gatekeeper-system -l app=gatekeeper --tail=50kubectl get endpoints -n gatekeeper-systemkubectl auth can-i create constrainttemplates --as=system:serviceaccount:gatekeeper-system:gatekeeper-admin造可複策模與特定約。
OPA Gatekeeper 約模:
# required-labels-template.yaml
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8srequiredlabels
annotations:
# ... (see EXAMPLES.md for complete configuration)
Kyverno ClusterPolicy:
# kyverno-policies.yaml
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: require-labels
annotations:
# ... (see EXAMPLES.md for complete configuration)
施策:
# Apply Gatekeeper templates and constraints
kubectl apply -f required-labels-template.yaml
# Apply Kyverno policies
kubectl apply -f kyverno-policies.yaml
# Verify constraint/policy status
kubectl get constraints
kubectl get clusterpolicies
# Check for any policy errors
kubectl describe k8srequiredlabels require-app-labels
kubectl describe clusterpolicy require-labels
得:ConstraintTemplates/ClusterPolicies 建成。約態顯「True」執行。策無誤。鈎始評新資源。
敗:
opa test 於本機或察約態kubectl apply --dry-run=client -f policy.yamlkubectl get constraint -o yaml | grep -A 10 status驗策阻非合而許合者。
造試單:
# test-non-compliant.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: test-no-labels
namespace: production
# ... (see EXAMPLES.md for complete configuration)
試策:
# Attempt to create non-compliant resource (should fail)
kubectl apply -f test-non-compliant.yaml
# Expected: Error with policy violation message
# Create compliant resource (should succeed)
kubectl apply -f test-compliant.yaml
# Expected: deployment.apps/test-compliant created
# Test with dry-run for validation
kubectl apply -f test-non-compliant.yaml --dry-run=server
# Shows policy violations without actually creating resource
# Clean up
kubectl delete -f test-compliant.yaml
試策報(Kyverno):
# Check policy reports
kubectl get policyreports -A
kubectl get clusterpolicyreports
# View detailed report
kubectl get policyreport -n production -o yaml
# Check policy rule results
kubectl get policyreport -n production -o jsonpath='{.items[0].results}' | jq .
得:非合者拒而示明違信。合者建成。策報示過/敗。乾跑驗不建資源。
敗:
validationFailureAction: auditkubectl logs -n gatekeeper-system -l app=gatekeeperkubectl run test --rm -it --image=busybox --restart=Never經變自動修復。
Gatekeeper 變:
# gatekeeper-mutations.yaml
apiVersion: mutations.gatekeeper.sh/v1beta1
kind: Assign
metadata:
name: add-default-labels
spec:
# ... (see EXAMPLES.md for complete configuration)
Kyverno 變策:
# kyverno-mutations.yaml
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: add-default-labels
spec:
# ... (see EXAMPLES.md for complete configuration)
施而試變:
# Apply mutation policies
kubectl apply -f gatekeeper-mutations.yaml
# OR
kubectl apply -f kyverno-mutations.yaml
# Test mutation with a deployment
# ... (see EXAMPLES.md for complete configuration)
得:變自動加標、源或改映像。布後資源顯變值。策引日記變。變無誤。
敗:
kubectl get mutatingwebhookconfigurationkubectl logs -n kyverno deploy/kyverno-admission-controller設審識舊資源之違而不阻。
Gatekeeper 審:
# Audit runs automatically based on auditInterval setting
# Check audit results
kubectl get constraints -o json | \
jq '.items[] | {name: .metadata.name, violations: .status.totalViolations}'
# Get detailed violation information
# ... (see EXAMPLES.md for complete configuration)
Kyverno 審與報:
# Generate policy reports for existing resources
kubectl create job --from=cronjob/kyverno-cleanup-controller -n kyverno manual-report-gen
# View policy reports
kubectl get policyreport -A
kubectl get clusterpolicyreport
# ... (see EXAMPLES.md for complete configuration)
造策合規儀表:
# prometheus-rules.yaml
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: policy-alerts
namespace: monitoring
# ... (see EXAMPLES.md for complete configuration)
得:審識舊資源違而不阻布。策報生過/敗計。違可出以閱。監計已露。違增時警。
敗:
kubectl get pods -n gatekeeper-system -l gatekeeper.sh/operation=auditkubectl logs -n gatekeeper-system -l gatekeeper.sh/operation=auditkubectl get constraint -o yaml | grep -A 20 status布前加策驗以左移行策。
CI/CD 入本:
#!/bin/bash
# validate-policies.sh
set -e
echo "=== Policy Validation for CI/CD ==="
# ... (see EXAMPLES.md for complete configuration)
GitHub Actions 工作流:
# .github/workflows/policy-validation.yaml
name: Policy Validation
on:
pull_request:
paths:
# ... (see EXAMPLES.md for complete configuration)
Pre-commit 鈎:
#!/bin/bash
# .git/hooks/pre-commit
# Validate Kubernetes manifests against policies
if git diff --cached --name-only | grep -E 'manifests/.*\.yaml#x27;; then
echo "Validating Kubernetes manifests against policies..."
# ... (see EXAMPLES.md for complete configuration)
得:CI/CD 管於布前驗單。策違敗管線並示明信。策報附於 PR。Pre-commit 鈎早捕違。發者於入群前聞策議。
敗:
kyverno apply policy.yaml --resource manifest.yamlfailurePolicy: Fail 於鈎無時阻諸資源。非要策用 Ignore,然知安全之虞。行前試鈎可用否kubectl api-resources 尋確值。通配符(*)便但損性能opa test 試,以 trace() 記,用 gator 離線試v1beta1 約,Kyverno v1.11 用 kyverno.io/v1。察文以定版manage-kubernetes-secrets - 密驗策security-audit-codebase - 互補之安掃deploy-to-kubernetes - 含策驗之應用布setup-service-mesh - 服務網授權策補入策configure-api-gateway - 關策與入策並行implement-gitops-workflow - 含策驗於管之 GitOps