[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M738PZ5RVE2CERCZCEAA3MD3":3,"skill-same:01M738PZ5RVE2CERCZCEAA3MD3":65},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":37,"commitSha":38,"skillDirectory":39,"forksCount":40,"repositoryHtmlUrl":41,"repositoryHomepageUrl":6,"ownerHtmlUrl":42,"ownerBlogUrl":43,"ownerDescription":6,"updatedAt":44,"install":45,"resources":58},"01M738PZ5RVE2CERCZCEAA3MD3","enforce-policy-as-code",null,"Implement 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\u002FCD pipelines for shift-left policy validation. Use when enforcing resource configuration standards, preventing security misconfigurations such as privileged containers, ensuring compliance before deployment, standardizing naming conventions, or auditing existing cluster resources against policies.","roohe\u002Fagentic-super-skills","roohe","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99054084?v=4","01M734WCDFP6RZVT5CNM00QR26","01M734WCE4BD0T4NZS5PCV9V5F",10,"MIT","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fenforce-policy-as-code\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: enforce-policy-as-code\nlocale: caveman-lite\nsource_locale: en\nsource_commit: 82c77053\ntranslator: \"Julius Brussee homage — caveman\"\ntranslation_date: \"2026-04-24\"\ndescription: >\n  Implement policy-as-code enforcement using OPA Gatekeeper or Kyverno to validate and mutate\n  Kubernetes resources according to organizational policies. Covers constraint templates,\n  admission control, audit mode, reporting violations, and integrating with CI\u002FCD pipelines\n  for shift-left policy validation. Use when enforcing resource configuration standards,\n  preventing security misconfigurations such as privileged containers, ensuring compliance\n  before deployment, standardizing naming conventions, or auditing existing cluster resources\n  against policies.\nlicense: MIT\nallowed-tools: Read Write Edit Bash Grep Glob\nmetadata:\n  author: Philipp Thoss\n  version: \"1.0\"\n  domain: devops\n  complexity: intermediate\n  language: multi\n  tags: opa, gatekeeper, kyverno, policy, admission-control, compliance, kubernetes\n---\n\n# Enforce Policy as Code\n\nImplement declarative policy enforcement using OPA Gatekeeper or Kyverno for Kubernetes resource validation and mutation.\n\n## When to Use\n\n- Enforce organizational standards for resource configuration (labels, annotations, limits)\n- Prevent security misconfigurations (privileged containers, host namespaces, insecure images)\n- Ensure compliance requirements are met before resources deployed\n- Standardize resource naming conventions and metadata\n- Implement automated remediation via mutation policies\n- Audit existing cluster resources against policies without blocking\n- Integrate policy validation into CI\u002FCD pipelines for shift-left approach\n\n## Inputs\n\n- **Required**: Kubernetes cluster with admin access\n- **Required**: Choice of policy engine (OPA Gatekeeper or Kyverno)\n- **Required**: List of policies to enforce (security, compliance, operational)\n- **Optional**: Existing resources to audit\n- **Optional**: Exemption\u002Fexclusion patterns for specific namespaces or resources\n- **Optional**: CI\u002FCD pipeline configuration for pre-deployment validation\n\n## Procedure\n\n> See [Extended Examples](references\u002FEXAMPLES.md) for complete configuration files and templates.\n\n\n### Step 1: Install Policy Engine\n\nDeploy OPA Gatekeeper or Kyverno as admission controller.\n\n**For OPA Gatekeeper:**\n```bash\n# Install Gatekeeper using Helm\nhelm repo add gatekeeper https:\u002F\u002Fopen-policy-agent.github.io\u002Fgatekeeper\u002Fcharts\nhelm repo update\n\n# Install with audit enabled\nhelm install gatekeeper gatekeeper\u002Fgatekeeper \\\n  --namespace gatekeeper-system \\\n  --create-namespace \\\n  --set audit.replicas=2 \\\n  --set replicas=3 \\\n  --set validatingWebhookFailurePolicy=Fail \\\n  --set auditInterval=60\n\n# Verify installation\nkubectl get pods -n gatekeeper-system\nkubectl get crd | grep gatekeeper\n\n# Check webhook configuration\nkubectl get validatingwebhookconfigurations gatekeeper-validating-webhook-configuration -o yaml\n```\n\n**For Kyverno:**\n```bash\n# Install Kyverno using Helm\nhelm repo add kyverno https:\u002F\u002Fkyverno.github.io\u002Fkyverno\u002F\nhelm repo update\n\n# Install with HA setup\nhelm install kyverno kyverno\u002Fkyverno \\\n  --namespace kyverno \\\n  --create-namespace \\\n  --set replicaCount=3 \\\n  --set admissionController.replicas=3 \\\n  --set backgroundController.replicas=2 \\\n  --set cleanupController.replicas=2\n\n# Verify installation\nkubectl get pods -n kyverno\nkubectl get crd | grep kyverno\n\n# Check webhook configurations\nkubectl get validatingwebhookconfigurations kyverno-resource-validating-webhook-cfg\nkubectl get mutatingwebhookconfigurations kyverno-resource-mutating-webhook-cfg\n```\n\nCreate namespace exclusions:\n```yaml\n# gatekeeper-config.yaml\napiVersion: config.gatekeeper.sh\u002Fv1alpha1\nkind: Config\nmetadata:\n  name: config\n  namespace: gatekeeper-system\nspec:\n  match:\n    - excludedNamespaces:\n      - kube-system\n      - kube-public\n      - kube-node-lease\n      - gatekeeper-system\n      processes:\n      - audit\n      - webhook\n  validation:\n    traces:\n      - user: system:serviceaccount:gatekeeper-system:gatekeeper-admin\n        kind:\n          group: \"\"\n          version: v1\n          kind: Namespace\n```\n\n**Got:** Policy engine pods running with multiple replicas. CRDs installed (ConstraintTemplate, Constraint for Gatekeeper; ClusterPolicy, Policy for Kyverno). Validating\u002Fmutating webhooks active. Audit controller running.\n\n**If fail:**\n- Check pod logs: `kubectl logs -n gatekeeper-system -l app=gatekeeper --tail=50`\n- Verify webhook endpoints reachable: `kubectl get endpoints -n gatekeeper-system`\n- Check for port conflicts or certificate issues in webhook logs\n- Ensure cluster has sufficient resources (policy engines need ~500MB per replica)\n- Review RBAC permissions: `kubectl auth can-i create constrainttemplates --as=system:serviceaccount:gatekeeper-system:gatekeeper-admin`\n\n### Step 2: Define Constraint Templates and Policies\n\nCreate reusable policy templates and specific constraints.\n\n**OPA Gatekeeper Constraint Template:**\n```yaml\n# required-labels-template.yaml\napiVersion: templates.gatekeeper.sh\u002Fv1\nkind: ConstraintTemplate\nmetadata:\n  name: k8srequiredlabels\n  annotations:\n# ... (see EXAMPLES.md for complete configuration)\n```\n\n**Kyverno ClusterPolicy:**\n```yaml\n# kyverno-policies.yaml\napiVersion: kyverno.io\u002Fv1\nkind: ClusterPolicy\nmetadata:\n  name: require-labels\n  annotations:\n# ... (see EXAMPLES.md for complete configuration)\n```\n\nApply policies:\n```bash\n# Apply Gatekeeper templates and constraints\nkubectl apply -f required-labels-template.yaml\n\n# Apply Kyverno policies\nkubectl apply -f kyverno-policies.yaml\n\n# Verify constraint\u002Fpolicy status\nkubectl get constraints\nkubectl get clusterpolicies\n\n# Check for any policy errors\nkubectl describe k8srequiredlabels require-app-labels\nkubectl describe clusterpolicy require-labels\n```\n\n**Got:** ConstraintTemplates\u002FClusterPolicies created successfully. Constraints show status \"True\" for enforcement. No errors in policy definitions. Webhook begins evaluating new resources against policies.\n\n**If fail:**\n- Validate Rego syntax (Gatekeeper): Use `opa test` locally or check constraint status\n- Check policy YAML syntax: `kubectl apply --dry-run=client -f policy.yaml`\n- Review constraint status: `kubectl get constraint -o yaml | grep -A 10 status`\n- Test with simple policy first, then add complexity\n- Verify match criteria (kinds, namespaces) are correct\n\n### Step 3: Test Policy Enforcement\n\nValidate policies block non-compliant resources and allow compliant ones.\n\nCreate test manifests:\n```yaml\n# test-non-compliant.yaml\napiVersion: apps\u002Fv1\nkind: Deployment\nmetadata:\n  name: test-no-labels\n  namespace: production\n# ... (see EXAMPLES.md for complete configuration)\n```\n\nTest policies:\n```bash\n# Attempt to create non-compliant resource (should fail)\nkubectl apply -f test-non-compliant.yaml\n# Expected: Error with policy violation message\n\n# Create compliant resource (should succeed)\nkubectl apply -f test-compliant.yaml\n# Expected: deployment.apps\u002Ftest-compliant created\n\n# Test with dry-run for validation\nkubectl apply -f test-non-compliant.yaml --dry-run=server\n# Shows policy violations without actually creating resource\n\n# Clean up\nkubectl delete -f test-compliant.yaml\n```\n\nTest with policy reporting (Kyverno):\n```bash\n# Check policy reports\nkubectl get policyreports -A\nkubectl get clusterpolicyreports\n\n# View detailed report\nkubectl get policyreport -n production -o yaml\n\n# Check policy rule results\nkubectl get policyreport -n production -o jsonpath='{.items[0].results}' | jq .\n```\n\n**Got:** Non-compliant resources rejected with clear violation messages. Compliant resources created successfully. Policy reports show pass\u002Ffail results. Dry-run validation works without creating resources.\n\n**If fail:**\n- Check if policy is in audit mode instead of enforce: `validationFailureAction: audit`\n- Verify webhook is processing requests: `kubectl logs -n gatekeeper-system -l app=gatekeeper`\n- Check for namespace exclusions that might exempt test namespace\n- Test webhook connectivity: `kubectl run test --rm -it --image=busybox --restart=Never`\n- Review webhook failure policy (Ignore vs Fail)\n\n### Step 4: Implement Mutation Policies\n\nConfigure automatic remediation through mutation.\n\n**Gatekeeper mutation:**\n```yaml\n# gatekeeper-mutations.yaml\napiVersion: mutations.gatekeeper.sh\u002Fv1beta1\nkind: Assign\nmetadata:\n  name: add-default-labels\nspec:\n# ... (see EXAMPLES.md for complete configuration)\n```\n\n**Kyverno mutation policies:**\n```yaml\n# kyverno-mutations.yaml\napiVersion: kyverno.io\u002Fv1\nkind: ClusterPolicy\nmetadata:\n  name: add-default-labels\nspec:\n# ... (see EXAMPLES.md for complete configuration)\n```\n\nApply and test mutations:\n```bash\n# Apply mutation policies\nkubectl apply -f gatekeeper-mutations.yaml\n# OR\nkubectl apply -f kyverno-mutations.yaml\n\n# Test mutation with a deployment\n# ... (see EXAMPLES.md for complete configuration)\n```\n\n**Got:** Mutations automatically add labels, resources, or modify images. Deployed resources show mutated values. Mutations logged in policy engine logs. No errors during mutation application.\n\n**If fail:**\n- Check mutation webhook is enabled: `kubectl get mutatingwebhookconfiguration`\n- Verify mutation policy syntax: especially JSON paths and conditions\n- Review logs: `kubectl logs -n kyverno deploy\u002Fkyverno-admission-controller`\n- Test mutations don't conflict (multiple mutations on same field)\n- Ensure mutation applied before validation (order matters)\n\n### Step 5: Enable Audit Mode and Reporting\n\nConfigure audit to identify violations in existing resources without blocking.\n\n**Gatekeeper audit:**\n```bash\n# Audit runs automatically based on auditInterval setting\n# Check audit results\nkubectl get constraints -o json | \\\n  jq '.items[] | {name: .metadata.name, violations: .status.totalViolations}'\n\n# Get detailed violation information\n# ... (see EXAMPLES.md for complete configuration)\n```\n\n**Kyverno audit and reporting:**\n```bash\n# Generate policy reports for existing resources\nkubectl create job --from=cronjob\u002Fkyverno-cleanup-controller -n kyverno manual-report-gen\n\n# View policy reports\nkubectl get policyreport -A\nkubectl get clusterpolicyreport\n# ... (see EXAMPLES.md for complete configuration)\n```\n\nCreate dashboard for policy compliance:\n```yaml\n# prometheus-rules.yaml\napiVersion: monitoring.coreos.com\u002Fv1\nkind: PrometheusRule\nmetadata:\n  name: policy-alerts\n  namespace: monitoring\n# ... (see EXAMPLES.md for complete configuration)\n```\n\n**Got:** Audit identifies violations in existing resources without blocking deployments. Policy reports generated with pass\u002Ffail counts. Violations exportable for review. Metrics exposed for monitoring. Alerts fire on increasing violations.\n\n**If fail:**\n- Verify audit controller running: `kubectl get pods -n gatekeeper-system -l gatekeeper.sh\u002Foperation=audit`\n- Check audit interval setting in installation\n- Review audit logs for errors: `kubectl logs -n gatekeeper-system -l gatekeeper.sh\u002Foperation=audit`\n- Ensure RBAC permissions allow reading all resource types for audit\n- Verify CRD status field being populated: `kubectl get constraint -o yaml | grep -A 20 status`\n\n### Step 6: Integrate with CI\u002FCD Pipeline\n\nAdd pre-deployment policy validation to shift-left policy enforcement.\n\n**CI\u002FCD integration script:**\n```bash\n#!\u002Fbin\u002Fbash\n# validate-policies.sh\n\nset -e\n\necho \"=== Policy Validation for CI\u002FCD ===\"\n# ... (see EXAMPLES.md for complete configuration)\n```\n\n**GitHub Actions workflow:**\n```yaml\n# .github\u002Fworkflows\u002Fpolicy-validation.yaml\nname: Policy Validation\nlocale: caveman-lite\nsource_locale: en\nsource_commit: 82c77053\ntranslator: \"Julius Brussee homage — caveman\"\ntranslation_date: \"2026-04-19\"\n\non:\n  pull_request:\n    paths:\n# ... (see EXAMPLES.md for complete configuration)\n```\n\n**Pre-commit hook:**\n```bash\n#!\u002Fbin\u002Fbash\n# .git\u002Fhooks\u002Fpre-commit\n\n# Validate Kubernetes manifests against policies\nif git diff --cached --name-only | grep -E 'manifests\u002F.*\\.yaml$'; then\n  echo \"Validating Kubernetes manifests against policies...\"\n# ... (see EXAMPLES.md for complete configuration)\n```\n\n**Got:** CI\u002FCD pipeline validates manifests before deployment. Policy violations fail pipeline with clear messages. Policy reports attached to PR. Pre-commit hooks catch violations early. Developers notified of policy issues before reaching cluster.\n\n**If fail:**\n- Verify CLI tools installed and in PATH\n- Check kubeconfig credentials valid for fetching policies\n- Test policy validation locally first: `kyverno apply policy.yaml --resource manifest.yaml`\n- Ensure policies synced from cluster are complete\n- Review policy CLI logs for specific validation errors\n\n## Validation\n\n- [ ] Policy engine pods running with HA configuration\n- [ ] Validating and mutating webhooks active and reachable\n- [ ] Constraint templates and policies created without errors\n- [ ] Non-compliant resources rejected with clear violation messages\n- [ ] Compliant resources deploy successfully\n- [ ] Mutation policies automatically remediate resources\n- [ ] Audit mode identifies violations in existing resources\n- [ ] Policy reports generated and accessible\n- [ ] Metrics exposed for policy compliance monitoring\n- [ ] CI\u002FCD pipeline validates manifests pre-deployment\n- [ ] Pre-commit hooks prevent policy violations\n- [ ] Namespace exclusions configured appropriately\n\n## Pitfalls\n\n- **Webhook Failure Policy**: `failurePolicy: Fail` blocks all resources if webhook unavailable. Use `Ignore` for non-critical policies, but understand security implications. Test webhook availability before enforcing.\n\n- **Too Restrictive Initial Policies**: Starting with enforcement mode on strict policies breaks existing workloads. Begin with audit mode, review violations, communicate with teams, then enforce gradually.\n\n- **Missing Resource Specifications**: Policies must specify API groups, versions, and kinds correctly. Use `kubectl api-resources` to find exact values. Wildcards (`*`) convenient but can cause performance issues.\n\n- **Mutation Order**: Mutations applied before validations. Ensure mutations don't conflict and that validations account for mutated values. Test mutation+validation together.\n\n- **Namespace Exclusions**: Excluding system namespaces necessary, but be careful not to over-exclude. Review exclusions regularly as policies mature.\n\n- **Rego Complexity (Gatekeeper)**: Complex Rego policies difficult to debug. Start simple, test with `opa test` locally, add logging with `trace()`, use gator for offline testing.\n\n- **Performance Impact**: Policy evaluation adds latency to admission. Keep policies efficient, use appropriate matching criteria, monitor webhook latency metrics.\n\n- **Policy Conflicts**: Multiple policies modifying same field cause issues. Coordinate policies across teams, use policy libraries for common patterns, test combinations.\n\n- **Background Scanning**: Background audit scans entire cluster. Can be resource-intensive in large clusters. Adjust audit interval based on cluster size and policy count.\n\n- **Version Compatibility**: Policy CRD versions change. Gatekeeper v3 uses `v1beta1` constraints, Kyverno v1.11 uses `kyverno.io\u002Fv1`. Check docs for your version.\n\n## Related Skills\n\n- `manage-kubernetes-secrets` - Secret validation policies\n- `security-audit-codebase` - Complementary security scanning\n- `deploy-to-kubernetes` - Application deployment with policy validation\n- `setup-service-mesh` - Service mesh authorization policies complement admission policies\n- `configure-api-gateway` - Gateway policies work alongside admission policies\n- `implement-gitops-workflow` - GitOps with policy validation in pipeline\n","# Enforce Policy as Code\n\nImplement declarative policy enforcement using OPA Gatekeeper or Kyverno for Kubernetes resource validation and mutation.\n\n## When to Use\n\n- Enforce organizational standards for resource configuration (labels, annotations, limits)\n- Prevent security misconfigurations (privileged containers, host namespaces, insecure images)\n- Ensure compliance requirements are met before resources deployed\n- Standardize resource naming conventions and metadata\n- Implement automated remediation via mutation policies\n- Audit existing cluster resources against policies without blocking\n- Integrate policy validation into CI\u002FCD pipelines for shift-left approach\n\n## Inputs\n\n- **Required**: Kubernetes cluster with admin access\n- **Required**: Choice of policy engine (OPA Gatekeeper or Kyverno)\n- **Required**: List of policies to enforce (security, compliance, operational)\n- **Optional**: Existing resources to audit\n- **Optional**: Exemption\u002Fexclusion patterns for specific namespaces or resources\n- **Optional**: CI\u002FCD pipeline configuration for pre-deployment validation\n\n## Procedure\n\n> See [Extended Examples](references\u002FEXAMPLES.md) for complete configuration files and templates.\n\n\n### Step 1: Install Policy Engine\n\nDeploy OPA Gatekeeper or Kyverno as admission controller.\n\n**For OPA Gatekeeper:**\n```bash\n# Install Gatekeeper using Helm\nhelm repo add gatekeeper https:\u002F\u002Fopen-policy-agent.github.io\u002Fgatekeeper\u002Fcharts\nhelm repo update\n\n# Install with audit enabled\nhelm install gatekeeper gatekeeper\u002Fgatekeeper \\\n  --namespace gatekeeper-system \\\n  --create-namespace \\\n  --set audit.replicas=2 \\\n  --set replicas=3 \\\n  --set validatingWebhookFailurePolicy=Fail \\\n  --set auditInterval=60\n\n# Verify installation\nkubectl get pods -n gatekeeper-system\nkubectl get crd | grep gatekeeper\n\n# Check webhook configuration\nkubectl get validatingwebhookconfigurations gatekeeper-validating-webhook-configuration -o yaml\n```\n\n**For Kyverno:**\n```bash\n# Install Kyverno using Helm\nhelm repo add kyverno https:\u002F\u002Fkyverno.github.io\u002Fkyverno\u002F\nhelm repo update\n\n# Install with HA setup\nhelm install kyverno kyverno\u002Fkyverno \\\n  --namespace kyverno \\\n  --create-namespace \\\n  --set replicaCount=3 \\\n  --set admissionController.replicas=3 \\\n  --set backgroundController.replicas=2 \\\n  --set cleanupController.replicas=2\n\n# Verify installation\nkubectl get pods -n kyverno\nkubectl get crd | grep kyverno\n\n# Check webhook configurations\nkubectl get validatingwebhookconfigurations kyverno-resource-validating-webhook-cfg\nkubectl get mutatingwebhookconfigurations kyverno-resource-mutating-webhook-cfg\n```\n\nCreate namespace exclusions:\n```yaml\n# gatekeeper-config.yaml\napiVersion: config.gatekeeper.sh\u002Fv1alpha1\nkind: Config\nmetadata:\n  name: config\n  namespace: gatekeeper-system\nspec:\n  match:\n    - excludedNamespaces:\n      - kube-system\n      - kube-public\n      - kube-node-lease\n      - gatekeeper-system\n      processes:\n      - audit\n      - webhook\n  validation:\n    traces:\n      - user: system:serviceaccount:gatekeeper-system:gatekeeper-admin\n        kind:\n          group: \"\"\n          version: v1\n          kind: Namespace\n```\n\n**Got:** Policy engine pods running with multiple replicas. CRDs installed (ConstraintTemplate, Constraint for Gatekeeper; ClusterPolicy, Policy for Kyverno). Validating\u002Fmutating webhooks active. Audit controller running.\n\n**If fail:**\n- Check pod logs: `kubectl logs -n gatekeeper-system -l app=gatekeeper --tail=50`\n- Verify webhook endpoints reachable: `kubectl get endpoints -n gatekeeper-system`\n- Check for port conflicts or certificate issues in webhook logs\n- Ensure cluster has sufficient resources (policy engines need ~500MB per replica)\n- Review RBAC permissions: `kubectl auth can-i create constrainttemplates --as=system:serviceaccount:gatekeeper-system:gatekeeper-admin`\n\n### Step 2: Define Constraint Templates and Policies\n\nCreate reusable policy templates and specific constraints.\n\n**OPA Gatekeeper Constraint Template:**\n```yaml\n# required-labels-template.yaml\napiVersion: templates.gatekeeper.sh\u002Fv1\nkind: ConstraintTemplate\nmetadata:\n  name: k8srequiredlabels\n  annotations:\n# ... (see EXAMPLES.md for complete configuration)\n```\n\n**Kyverno ClusterPolicy:**\n```yaml\n# kyverno-policies.yaml\napiVersion: kyverno.io\u002Fv1\nkind: ClusterPolicy\nmetadata:\n  name: require-labels\n  annotations:\n# ... (see EXAMPLES.md for complete configuration)\n```\n\nApply policies:\n```bash\n# Apply Gatekeeper templates and constraints\nkubectl apply -f required-labels-template.yaml\n\n# Apply Kyverno policies\nkubectl apply -f kyverno-policies.yaml\n\n# Verify constraint\u002Fpolicy status\nkubectl get constraints\nkubectl get clusterpolicies\n\n# Check for any policy errors\nkubectl describe k8srequiredlabels require-app-labels\nkubectl describe clusterpolicy require-labels\n```\n\n**Got:** ConstraintTemplates\u002FClusterPolicies created successfully. Constraints show status \"True\" for enforcement. No errors in policy definitions. Webhook begins evaluating new resources against policies.\n\n**If fail:**\n- Validate Rego syntax (Gatekeeper): Use `opa test` locally or check constraint status\n- Check policy YAML syntax: `kubectl apply --dry-run=client -f policy.yaml`\n- Review constraint status: `kubectl get constraint -o yaml | grep -A 10 status`\n- Test with simple policy first, then add complexity\n- Verify match criteria (kinds, namespaces) are correct\n\n### Step 3: Test Policy Enforcement\n\nValidate policies block non-compliant resources and allow compliant ones.\n\nCreate test manifests:\n```yaml\n# test-non-compliant.yaml\napiVersion: apps\u002Fv1\nkind: Deployment\nmetadata:\n  name: test-no-labels\n  namespace: production\n# ... (see EXAMPLES.md for complete configuration)\n```\n\nTest policies:\n```bash\n# Attempt to create non-compliant resource (should fail)\nkubectl apply -f test-non-compliant.yaml\n# Expected: Error with policy violation message\n\n# Create compliant resource (should succeed)\nkubectl apply -f test-compliant.yaml\n# Expected: deployment.apps\u002Ftest-compliant created\n\n# Test with dry-run for validation\nkubectl apply -f test-non-compliant.yaml --dry-run=server\n# Shows policy violations without actually creating resource\n\n# Clean up\nkubectl delete -f test-compliant.yaml\n```\n\nTest with policy reporting (Kyverno):\n```bash\n# Check policy reports\nkubectl get policyreports -A\nkubectl get clusterpolicyreports\n\n# View detailed report\nkubectl get policyreport -n production -o yaml\n\n# Check policy rule results\nkubectl get policyreport -n production -o jsonpath='{.items[0].results}' | jq .\n```\n\n**Got:** Non-compliant resources rejected with clear violation messages. Compliant resources created successfully. Policy reports show pass\u002Ffail results. Dry-run validation works without creating resources.\n\n**If fail:**\n- Check if policy is in audit mode instead of enforce: `validationFailureAction: audit`\n- Verify webhook is processing requests: `kubectl logs -n gatekeeper-system -l app=gatekeeper`\n- Check for namespace exclusions that might exempt test namespace\n- Test webhook connectivity: `kubectl run test --rm -it --image=busybox --restart=Never`\n- Review webhook failure policy (Ignore vs Fail)\n\n### Step 4: Implement Mutation Policies\n\nConfigure automatic remediation through mutation.\n\n**Gatekeeper mutation:**\n```yaml\n# gatekeeper-mutations.yaml\napiVersion: mutations.gatekeeper.sh\u002Fv1beta1\nkind: Assign\nmetadata:\n  name: add-default-labels\nspec:\n# ... (see EXAMPLES.md for complete configuration)\n```\n\n**Kyverno mutation policies:**\n```yaml\n# kyverno-mutations.yaml\napiVersion: kyverno.io\u002Fv1\nkind: ClusterPolicy\nmetadata:\n  name: add-default-labels\nspec:\n# ... (see EXAMPLES.md for complete configuration)\n```\n\nApply and test mutations:\n```bash\n# Apply mutation policies\nkubectl apply -f gatekeeper-mutations.yaml\n# OR\nkubectl apply -f kyverno-mutations.yaml\n\n# Test mutation with a deployment\n# ... (see EXAMPLES.md for complete configuration)\n```\n\n**Got:** Mutations automatically add labels, resources, or modify images. Deployed resources show mutated values. Mutations logged in policy engine logs. No errors during mutation application.\n\n**If fail:**\n- Check mutation webhook is enabled: `kubectl get mutatingwebhookconfiguration`\n- Verify mutation policy syntax: especially JSON paths and conditions\n- Review logs: `kubectl logs -n kyverno deploy\u002Fkyverno-admission-controller`\n- Test mutations don't conflict (multiple mutations on same field)\n- Ensure mutation applied before validation (order matters)\n\n### Step 5: Enable Audit Mode and Reporting\n\nConfigure audit to identify violations in existing resources without blocking.\n\n**Gatekeeper audit:**\n```bash\n# Audit runs automatically based on auditInterval setting\n# Check audit results\nkubectl get constraints -o json | \\\n  jq '.items[] | {name: .metadata.name, violations: .status.totalViolations}'\n\n# Get detailed violation information\n# ... (see EXAMPLES.md for complete configuration)\n```\n\n**Kyverno audit and reporting:**\n```bash\n# Generate policy reports for existing resources\nkubectl create job --from=cronjob\u002Fkyverno-cleanup-controller -n kyverno manual-report-gen\n\n# View policy reports\nkubectl get policyreport -A\nkubectl get clusterpolicyreport\n# ... (see EXAMPLES.md for complete configuration)\n```\n\nCreate dashboard for policy compliance:\n```yaml\n# prometheus-rules.yaml\napiVersion: monitoring.coreos.com\u002Fv1\nkind: PrometheusRule\nmetadata:\n  name: policy-alerts\n  namespace: monitoring\n# ... (see EXAMPLES.md for complete configuration)\n```\n\n**Got:** Audit identifies violations in existing resources without blocking deployments. Policy reports generated with pass\u002Ffail counts. Violations exportable for review. Metrics exposed for monitoring. Alerts fire on increasing violations.\n\n**If fail:**\n- Verify audit controller running: `kubectl get pods -n gatekeeper-system -l gatekeeper.sh\u002Foperation=audit`\n- Check audit interval setting in installation\n- Review audit logs for errors: `kubectl logs -n gatekeeper-system -l gatekeeper.sh\u002Foperation=audit`\n- Ensure RBAC permissions allow reading all resource types for audit\n- Verify CRD status field being populated: `kubectl get constraint -o yaml | grep -A 20 status`\n\n### Step 6: Integrate with CI\u002FCD Pipeline\n\nAdd pre-deployment policy validation to shift-left policy enforcement.\n\n**CI\u002FCD integration script:**\n```bash\n#!\u002Fbin\u002Fbash\n# validate-policies.sh\n\nset -e\n\necho \"=== Policy Validation for CI\u002FCD ===\"\n# ... (see EXAMPLES.md for complete configuration)\n```\n\n**GitHub Actions workflow:**\n```yaml\n# .github\u002Fworkflows\u002Fpolicy-validation.yaml\nname: Policy Validation\nlocale: caveman-lite\nsource_locale: en\nsource_commit: 82c77053\ntranslator: \"Julius Brussee homage — caveman\"\ntranslation_date: \"2026-04-19\"\n\non:\n  pull_request:\n    paths:\n# ... (see EXAMPLES.md for complete configuration)\n```\n\n**Pre-commit hook:**\n```bash\n#!\u002Fbin\u002Fbash\n# .git\u002Fhooks\u002Fpre-commit\n\n# Validate Kubernetes manifests against policies\nif git diff --cached --name-only | grep -E 'manifests\u002F.*\\.yaml$'; then\n  echo \"Validating Kubernetes manifests against policies...\"\n# ... (see EXAMPLES.md for complete configuration)\n```\n\n**Got:** CI\u002FCD pipeline validates manifests before deployment. Policy violations fail pipeline with clear messages. Policy reports attached to PR. Pre-commit hooks catch violations early. Developers notified of policy issues before reaching cluster.\n\n**If fail:**\n- Verify CLI tools installed and in PATH\n- Check kubeconfig credentials valid for fetching policies\n- Test policy validation locally first: `kyverno apply policy.yaml --resource manifest.yaml`\n- Ensure policies synced from cluster are complete\n- Review policy CLI logs for specific validation errors\n\n## Validation\n\n- [ ] Policy engine pods running with HA configuration\n- [ ] Validating and mutating webhooks active and reachable\n- [ ] Constraint templates and policies created without errors\n- [ ] Non-compliant resources rejected with clear violation messages\n- [ ] Compliant resources deploy successfully\n- [ ] Mutation policies automatically remediate resources\n- [ ] Audit mode identifies violations in existing resources\n- [ ] Policy reports generated and accessible\n- [ ] Metrics exposed for policy compliance monitoring\n- [ ] CI\u002FCD pipeline validates manifests pre-deployment\n- [ ] Pre-commit hooks prevent policy violations\n- [ ] Namespace exclusions configured appropriately\n\n## Pitfalls\n\n- **Webhook Failure Policy**: `failurePolicy: Fail` blocks all resources if webhook unavailable. Use `Ignore` for non-critical policies, but understand security implications. Test webhook availability before enforcing.\n\n- **Too Restrictive Initial Policies**: Starting with enforcement mode on strict policies breaks existing workloads. Begin with audit mode, review violations, communicate with teams, then enforce gradually.\n\n- **Missing Resource Specifications**: Policies must specify API groups, versions, and kinds correctly. Use `kubectl api-resources` to find exact values. Wildcards (`*`) convenient but can cause performance issues.\n\n- **Mutation Order**: Mutations applied before validations. Ensure mutations don't conflict and that validations account for mutated values. Test mutation+validation together.\n\n- **Namespace Exclusions**: Excluding system namespaces necessary, but be careful not to over-exclude. Review exclusions regularly as policies mature.\n\n- **Rego Complexity (Gatekeeper)**: Complex Rego policies difficult to debug. Start simple, test with `opa test` locally, add logging with `trace()`, use gator for offline testing.\n\n- **Performance Impact**: Policy evaluation adds latency to admission. Keep policies efficient, use appropriate matching criteria, monitor webhook latency metrics.\n\n- **Policy Conflicts**: Multiple policies modifying same field cause issues. Coordinate policies across teams, use policy libraries for common patterns, test combinations.\n\n- **Background Scanning**: Background audit scans entire cluster. Can be resource-intensive in large clusters. Adjust audit interval based on cluster size and policy count.\n\n- **Version Compatibility**: Policy CRD versions change. Gatekeeper v3 uses `v1beta1` constraints, Kyverno v1.11 uses `kyverno.io\u002Fv1`. Check docs for your version.\n\n## Related Skills\n\n- `manage-kubernetes-secrets` - Secret validation policies\n- `security-audit-codebase` - Complementary security scanning\n- `deploy-to-kubernetes` - Application deployment with policy validation\n- `setup-service-mesh` - Service mesh authorization policies complement admission policies\n- `configure-api-gateway` - Gateway policies work alongside admission policies\n- `implement-gitops-workflow` - GitOps with policy validation in pipeline\n",{"name":5,"locale":23,"license":14,"metadata":24,"translator":31,"description":32,"allowed-tools":33,"source_commit":34,"source_locale":35,"translation_date":36},"caveman-lite",{"tags":25,"author":26,"domain":27,"version":28,"language":29,"complexity":30},"opa, gatekeeper, kyverno, policy, admission-control, compliance, kubernetes","Philipp Thoss","devops","1.0","multi","intermediate","Julius Brussee homage — caveman","Implement 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\u002FCD pipelines for shift-left policy validation. Use when enforcing resource configuration standards, preventing security misconfigurations such as privileged containers, ensuring compliance before deployment, standardizing naming conventions, or auditing existing cluster resources against policies.\n","Read Write Edit Bash Grep Glob","82c77053","en","2026-04-24","master","f483e54f3ad5f202a77d45f2e57f8d970b71195f","skills_library\u002Fenforce-policy-as-code",2,"https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills","https:\u002F\u002Fgithub.com\u002Froohe","yoou.link","2026-05-19 15:56:07",{"source":8,"skillName":5,"commands":46,"prompt":56,"zipAvailable":57},[47,50,53],{"tool":48,"command":49},"npx","npx skills add roohe\u002Fagentic-super-skills --skill enforce-policy-as-code",{"tool":51,"command":52},"bunx","bunx skills add roohe\u002Fagentic-super-skills --skill enforce-policy-as-code",{"tool":54,"command":55},"pnpm","pnpm dlx skills add roohe\u002Fagentic-super-skills --skill enforce-policy-as-code","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fenforce-policy-as-code\u002FSKILL.md",true,[59],{"path":60,"resourceType":61,"resourceTypeDesc":62,"sizeBytes":63,"sourceHtmlUrl":64},"references\u002FEXAMPLES.md","REFERENCE","参考文档",18717,"https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fenforce-policy-as-code\u002Freferences\u002FEXAMPLES.md",[66,73,80,87,94,101],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":18},"01M73D865CZME2FCMKA4PQM348","zarr-python","Chunked N-D arrays for cloud storage. Compressed arrays, parallel I\u002FO, S3\u002FGCS integration, NumPy\u002FDask\u002FXarray compatible, for large-scale scientific computing pipelines.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fzarr-python\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":18},"01M73D7Z64J4ABWZJD7P44XBBF","youtube-downloader","Download and process YouTube content for research. Use when: downloading competitor videos for analysis; extracting audio for podcasts; getting transcripts for content repurposing; archiving webinars; research content curation","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fyoutube-downloader\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":18},"01M73D7K8778TGZV3GJFR3703D","yc-pitch-deck","Create a compelling startup pitch deck that follows the structure proven to raise billions from top investors. Master the YC and Sequoia formats that get founders funded. Use when: **Fundraising** to create investor pitch decks; **YC application** to structure your narrative; **Demo Day prep** to craft your 2-minute pitch; **Angel investors** to communicate your opportunity; **Partnership pitches** to structure compelling asks","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fyc-pitch-deck\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":18},"01M73D70KJSE0E8Z28YMNNRT04","x-twitter-scraper","Use when the user needs X (Twitter) data or confirmation-gated X actions through Xquik: tweet search, user lookup, follower extraction, media download, monitoring, webhooks, MCP, SDKs, posting, likes, DMs, and profile updates. Requires a Xquik API key. Never ask for X login material.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fx-twitter-scraper\u002FSKILL.md",[],[],{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":18},"01M73D6ED01GV077R7K4NZNFZJ","write-vignette","Create R package vignettes using R Markdown or Quarto. Covers vignette setup, YAML configuration, code chunk options, building and testing, and CRAN requirements for vignettes. Use when adding a Getting Started tutorial, documenting complex workflows spanning multiple functions, creating domain-specific guides, or when CRAN submission requires user-facing documentation beyond function help pages.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fwrite-vignette\u002FSKILL.md",[],[],{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":107,"publishedAt":18},"01M73D69YJR0BK3NFHE0CYG3EF","write-validation-documentation","Write IQ\u002FOQ\u002FPQ validation documentation for computerized systems in regulated environments. Covers protocols, reports, test scripts, deviation handling, and approval workflows. Use when validating R or other software for regulated use, preparing for a regulatory audit, documenting qualification of computing environments, or creating and updating validation protocols and reports for new or re-qualified systems.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fwrite-validation-documentation\u002FSKILL.md",[],[]]