enforce-policy-as-code
정보
이 스킬은 OPA Gatekeeper 또는 Kyverno를 사용하여 조직 정책에 맞춰 Kubernetes 리소스를 검증하고 변환하는 정책-코드(Policy-as-Code) 시행을 구현합니다. 승인 제어, 감사 모드, 그리고 좌측 이동(shift-left) 검증을 위한 CI/CD 통합을 다룹니다. 이를 통해 구성 표준을 시행하고, 보안 오설정을 방지하며, 배포 전에 규정 준수를 보장할 수 있습니다.
빠른 설치
Claude Code
추천npx skills add pjt222/agent-almanac -a claude-code/plugin add https://github.com/pjt222/agent-almanacgit clone https://github.com/pjt222/agent-almanac.git ~/.claude/skills/enforce-policy-as-codeClaude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요
문서
Enforce Policy as Code
Declarative policy enforce → OPA Gatekeeper or Kyverno. K8s resource validate + mutate.
Use When
- Enforce org standards (labels, annotations, limits)
- Prevent security misconfig (privileged containers, host namespaces, insecure images)
- Compliance before deploy
- Standardize naming + metadata
- Auto remediate via mutation
- Audit existing resources no block
- CI/CD shift-left
In
- Required: K8s cluster w/ admin
- Required: Engine choice (OPA Gatekeeper or Kyverno)
- Required: Policy list (security, compliance, ops)
- Optional: Existing resources to audit
- Optional: Exemption patterns (namespaces/resources)
- Optional: CI/CD config for pre-deploy validate
Do
See Extended Examples for complete configuration files and templates.
Step 1: Install Engine
Deploy OPA Gatekeeper or Kyverno as admission controller.
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
NS exclusions:
# 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
→ Engine pods HA. CRDs installed (ConstraintTemplate, Constraint / ClusterPolicy, Policy). Webhooks active. Audit running.
If err:
- Pod logs:
kubectl logs -n gatekeeper-system -l app=gatekeeper --tail=50 - Endpoints:
kubectl get endpoints -n gatekeeper-system - Port/cert issues in webhook logs
- Resources sufficient (~500MB/replica)
- RBAC:
kubectl auth can-i create constrainttemplates --as=system:serviceaccount:gatekeeper-system:gatekeeper-admin
Step 2: Define Templates + Policies
Reusable templates + constraints.
OPA Gatekeeper Template:
# 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:
# 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
→ Templates/Policies created. Status "True" enforce. No err. Webhook evals new resources.
If err:
- Rego syntax (Gatekeeper):
opa testlocally or check status - YAML:
kubectl apply --dry-run=client -f policy.yaml - Status:
kubectl get constraint -o yaml | grep -A 10 status - Simple first, add complexity
- Match criteria correct (kinds, namespaces)
Step 3: Test Enforcement
Validate block non-compliant, allow compliant.
Test manifests:
# test-non-compliant.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: test-no-labels
namespace: production
# ... (see EXAMPLES.md for complete configuration)
Test:
# 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
Policy reporting (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 .
→ Non-compliant rejected w/ clear msg. Compliant created. Reports show pass/fail. Dry-run works.
If err:
- Audit mode not enforce:
validationFailureAction: audit - Webhook processing:
kubectl logs -n gatekeeper-system -l app=gatekeeper - NS exclusions exempting test ns
- Webhook connectivity:
kubectl run test --rm -it --image=busybox --restart=Never - Failure policy (Ignore vs Fail)
Step 4: Mutation Policies
Auto remediate via mutation.
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 + test:
# 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)
→ Mutations auto add labels/resources/modify images. Mutated values visible. Logged. No err.
If err:
- Mutation webhook enabled:
kubectl get mutatingwebhookconfiguration - Syntax: JSON paths + conditions
- Logs:
kubectl logs -n kyverno deploy/kyverno-admission-controller - No conflicts (multiple mutations same field)
- Mutation before validation (order matters)
Step 5: Audit + Reporting
Audit identifies violations no block.
Gatekeeper audit:
# 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 audit + reporting:
# 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)
Dashboard:
# prometheus-rules.yaml
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: policy-alerts
namespace: monitoring
# ... (see EXAMPLES.md for complete configuration)
→ Audit finds violations no block. Reports generated pass/fail. Exportable. Metrics. Alerts.
If err:
- Audit controller:
kubectl get pods -n gatekeeper-system -l gatekeeper.sh/operation=audit - Audit interval setting
- Audit logs:
kubectl logs -n gatekeeper-system -l gatekeeper.sh/operation=audit - RBAC read all resource types
- CRD status populated:
kubectl get constraint -o yaml | grep -A 20 status
Step 6: CI/CD Integration
Pre-deploy validation → shift-left.
CI/CD script:
#!/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$'; then
echo "Validating Kubernetes manifests against policies..."
# ... (see EXAMPLES.md for complete configuration)
→ Pipeline validates pre-deploy. Violations fail w/ clear msg. Reports on PR. Pre-commit catches early. Devs notified pre-cluster.
If err:
- CLI tools in PATH
- kubeconfig creds valid
- Test locally:
kyverno apply policy.yaml --resource manifest.yaml - Policies synced complete
- Policy CLI logs for specific errs
Check
- Engine pods HA
- Webhooks active + reachable
- Templates + policies created no err
- Non-compliant rejected clear msg
- Compliant deploy OK
- Mutations auto remediate
- Audit finds violations existing
- Reports generated + accessible
- Metrics exposed
- CI/CD validates pre-deploy
- Pre-commit prevents
- NS exclusions appropriate
Traps
- Webhook Failure Policy:
failurePolicy: Failblocks all if webhook down.Ignorenon-critical, understand security. Test availability before enforce. - Too Strict Initial: Strict enforce breaks workloads. Audit first, review, communicate, enforce gradual.
- Missing Resource Specs: Must specify API groups/versions/kinds.
kubectl api-resources. Wildcards (*) convenient but slow. - Mutation Order: Mutation before validation. No conflicts. Test together.
- NS Exclusions: Exclude system ns necessary but not over-exclude. Review regularly.
- Rego Complexity (Gatekeeper): Complex Rego hard debug. Simple first,
opa testlocally,trace()logging, gator offline. - Perf Impact: Policy eval adds latency. Efficient policies, right match criteria, monitor webhook latency.
- Policy Conflicts: Multiple policies same field → issues. Coordinate teams, policy libs, test combos.
- Bg Scanning: Full cluster scan expensive large clusters. Adjust interval.
- Version Compat: CRD versions change. Gatekeeper v3 →
v1beta1, Kyverno v1.11 →kyverno.io/v1. Check docs.
→
manage-kubernetes-secrets- Secret validation policiessecurity-audit-codebase- Complementary security scanningdeploy-to-kubernetes- App deployment w/ policy validatesetup-service-mesh- Mesh authz policies complement admissionconfigure-api-gateway- Gateway policies alongside admissionimplement-gitops-workflow- GitOps w/ policy validate in pipeline
GitHub 저장소
연관 스킬
content-collections
메타이 스킬은 콘텐츠 콜렉션(Content Collections)을 위한 프로덕션 검증된 설정을 제공합니다. 콘텐츠 콜렉션은 Markdown/MDX 파일을 Zod 검증이 포함된 타입 안전한 데이터 콜렉션으로 변환해주는 TypeScript 최우선 도구입니다. 블로그, 문서 사이트 또는 콘텐츠 중심의 Vite + React 애플리케이션을 구축할 때 타입 안전성과 자동 콘텐츠 검증을 보장하기 위해 사용하세요. Vite 플러그인 구성과 MDX 컴파일부터 배포 최적화 및 스키마 검증에 이르기까지 모든 것을 다룹니다.
polymarket
메타이 스킬은 개발자들이 Polymarket 예측 시장 플랫폼을 활용한 애플리케이션을 구축할 수 있도록 지원하며, 거래 및 시장 데이터를 위한 API 통합 기능을 포함합니다. 또한 WebSocket을 통한 실시간 데이터 스트리밍을 제공하여 실시간 거래와 시장 활동을 모니터링할 수 있습니다. 이를 통해 거래 전략을 구현하거나 실시간 시장 업데이트를 처리하는 도구를 생성하는 데 활용할 수 있습니다.
creating-opencode-plugins
메타이 스킬은 개발자들이 명령어, 파일, LSP 작업 등 25개 이상의 이벤트 유형에 연결되는 OpenCode 플러그인을 만들 수 있도록 돕습니다. JavaScript/TypeScript 모듈을 위한 플러그인 구조, 이벤트 API 명세, 구현 패턴을 제공합니다. OpenCode AI 어시스턴트의 라이프사이클을 사용자 정의 이벤트 기반 로직으로 가로채거나, 모니터링하거나, 확장해야 할 때 사용하세요.
sglang
메타SGLang은 RadixAttention 프리픽스 캐싱을 활용하여 JSON, 정규식, 에이전트 워크플로우를 위한 고속 구조화 생성에 특화된 고성능 LLM 서빙 프레임워크입니다. 특히 반복되는 프리픽스가 있는 작업에서 상당히 빠른 추론 속도를 제공하여 복잡한 구조화 출력 및 다중 턴 대화에 이상적입니다. 제약 디코딩이 필요하거나 광범위한 프리픽스 공유가 있는 애플리케이션을 구축할 때는 vLLM과 같은 대안보다 SGLang을 선택하십시오.
