Kyverno label enforcement

From paulpas/agent-skill-router · View interactive version

Kyverno label enforcement is an AI agent skill from the GitHub repository paulpas/agent-skill-router. Enforces required labels on Pods and Namespaces using Kyverno validate rules with pattern matching and CEL expressions for compliance tracking.

How to use this skill

Skill file

Kyverno Label Enforcement

Enforces required labels on Pods and Namespaces using Kyverno validate rules with pattern matching and CEL expressions. When loaded, this skill makes the model design validation policies that ensure every workload and namespace carries the labels required for cost tracking, compliance, and operational standards — rejecting resources that lack required label keys or invalid value formats.

TL;DR Checklist

When to Use

When NOT to Use


Core Workflow

  1. Define the required label set — Identify the exact label keys and value constraints that must be present on target resources. Determine which label values are valid (using regex patterns) and which are mandatory (non-empty checks). Checkpoint: Create a documented list of required labels with their expected key format, value constraints, and validation rules.
  1. Create the validate rule with pattern matching — Build a ClusterPolicy with a validate rule using pattern matching to require specific label keys with non-empty values. For advanced validation, use CEL expressions with the matches() function to enforce value format constraints. Checkpoint: Verify the pattern uses "?*" for non-empty string validation, CEL matches() for regex-based value checks, and that the resource kind selector targets the right workload types.
  1. Deploy and monitor violations — Apply the policy and verify resources without required labels are rejected. Check PolicyReport for fail results and track violations over time. Consider pairing with a mutation policy to auto-inject missing labels. Checkpoint: Confirm PolicyReport shows pass for compliant resources and fail with descriptive messages for non-compliant ones.

Implementation Patterns

Pattern 1: Required Labels with Pattern Matching on Pods

Deploy a ClusterPolicy that enforces three required labels on all Pods: app.kubernetes.io/name, app.kubernetes.io/instance, and app.kubernetes.io/version. Uses pattern matching with "?*" to require non-empty string values.

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: require-app-labels
  annotations:
    policies.kyverno.io/title: Require App Labels on Pods
    policies.kyverno.io/category: Operational Standards
    policies.kyverno.io/description: >-
      Enforces the use of app.kubernetes.io labels on all Pods
      to support service discovery and compliance tracking.
spec:
  validationFailureAction: Enforce
  rules:
    - name: require-app-kubernetes-labels
      match:
        any:
          - resources:
              kinds:
                - Pod
      preconditions:
        all:
          - key: "{{ request.namespace }}"
            operator: NotIn
            value:
              - kube-system
              - kyverno
              - istio-system
      validate:
        message: "Labels app.kubernetes.io/name, app.kubernetes.io/instance, and app.kubernetes.io/version are required."
        pattern:
          metadata:
            labels:
              app.kubernetes.io/name: "?*"
              app.kubernetes.io/instance: "?*"
              app.kubernetes.io/version: "?*"

PolicyReport Example for Label Validation:

apiVersion: wgpolicyk8s.io/v1alpha2
kind: PolicyReport
metadata:
  name: require-app-labels-report
  namespace: default
results:
  - policy: require-app-labels
    rule: require-app-kubernetes-labels
    result: pass
    severity: medium
    message: "Resource passed policy check"
    scored: true
    source: kyverno
    timestamp:
      seconds: 1733501530
  - policy: require-app-labels
    rule: require-app-kubernetes-labels
    result: fail
    severity: medium
    message: "Labels app.kubernetes.io/name, app.kubernetes.io/instance, and app.kubernetes.io/version are required."
    scored: true
    source: kyverno
    resources:
      - name: my-pod
        kind: Pod
summary:
  error: 0
  fail: 1
  pass: 1
  skip: 0
  warn: 0

Pattern 2: Kubecost Multi-Label Policy with CEL Validation

Implement a comprehensive multi-label policy inspired by Kubecost's cost tracking requirements. This policy enforces five required labels (owner, team, department, app, env) with CEL-based regex validation on label values to ensure they follow naming conventions.

# ❌ BAD — No value format validation; accepts any non-empty value
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: bad-label-enforcement
spec:
  rules:
    - name: require-cost-labels
      validate:
        message: "Required labels missing"
        pattern:
          metadata:
            labels:
              owner: "?*"
              team: "?*"

# ✅ GOOD — Multi-label with CEL regex validation on values
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: require-cost-allocation-labels
  annotations:
    policies.kyverno.io/title: Require Cost Allocation Labels
    policies.kyverno.io/category: FinOps
    policies.kyverno.io/description: >-
      Enforces Kubecost-compatible cost allocation labels on all Pods
      with regex validation for naming conventions.
spec:
  validationFailureAction: Enforce
  background: false
  rules:
    - name: enforce-cost-labels
      match:
        any:
          - resources:
              kinds:
                - Pod
      preconditions:
        all:
          - key: "{{ request.namespace }}"
            operator: NotIn
            value:
              - kube-system
              - kyverno
      validate:
        message: >-
          Required cost allocation labels (owner, team, department, app, env)
          must be present and follow the format: lowercase alphanumeric with hyphens.
        pattern:
          metadata:
            labels:
              owner: "?*"
              team: "?*"
              department: "?*"
              app: "?*"
              env: "?*"
        any:
          - rule: enforce-owner-format
            match:
              any:
                - resources:
                    kinds:
                      - Pod
            validate:
              message: "Label 'owner' must match format: lowercase alphanumeric with hyphens (e.g., 'john-doe', 'team-alpha')."
              deny:
                conditions:
                  any:
                    - key: "{{ request.object.metadata.labels.owner }}"
                      operator: NotMatches
                      value: "[a-z0-9][a-z0-9-]{0,62}"
          - rule: enforce-env-format
            match:
              any:
                - resources:
                    kinds:
                      - Pod
            validate:
              message: "Label 'env' must be one of: production, staging, development, testing."
              deny:
                conditions:
                  any:
                    - key: "{{ request.object.metadata.labels.env }}"
                      operator: NotIn
                      value:
                        - production
                        - staging
                        - development
                        - testing

Pattern 3: Namespace-Level Label Enforcement

Enforce required labels on Namespaces to support resource governance and cost tracking at the namespace level. This pattern uses the Namespace kind in the match conditions and validates a separate set of governance labels.

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: require-namespace-labels
  annotations:
    policies.kyverno.io/title: Require Namespace Labels
    policies.kyverno.io/category: Resource Governance
    policies.kyverno.io/description: >-
      Enforces governance labels on all Namespaces including owner, team,
      and compliance tags for resource attribution and audit trails.
spec:
  validationFailureAction: Enforce
  rules:
    - name: require-governance-labels
      match:
        any:
          - resources:
              kinds:
                - Namespace
      preconditions:
        all:
          - key: "{{ request.namespace }}"
            operator: NotIn
            value:
              - kube-system
              - kube-public
              - kube-node-lease
      validate:
        message: "Namespaces require governance labels: owner, team, and compliance-tier."
        pattern:
          metadata:
            labels:
              owner: "?*"
              team: "?*"
              compliance-tier: "?*"

Constraints

MUST DO

MUST NOT DO


Related Skills

| Skill | Purpose |

|---|---|

| kyverno-mutate-patterns | Auto-inject missing labels to complement enforcement |

| kyverno-resource-quota-validation | Validate resource quotas alongside label requirements |


Live References

Authoritative documentation links for Kyverno label enforcement.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.