Kyverno 策略配置用例

本文档基于 Kyverno 提供核心策略配置用例。它帮助你在 Kubernetes 集群中基于 Namespace 或 Project 实现资源自动变更、统一配置,以及安全模板和基础环境的自动注入。

1. 资源变更与统一配置(Mutate)

Kyverno 的 Mutate 规则可以在准入控制阶段自动修改提交的资源。以下示例展示了如何为某个 namespace 下的所有 Pod 注入统一标签,并强制统一的 restartPolicy

1.1 向 Pod 注入统一标签

此策略会自动为集群中新创建的所有 Pod(或特定 namespace 内的 Pod)追加预设标签。这通常用于统一项目管理和计费调度。

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: add-default-pod-labels
  annotations:
    policies.kyverno.io/title: Add Default Pod Labels
    policies.kyverno.io/subject: Pod
    policies.kyverno.io/description: >-
      Automatically inject default labels into newly created Pods.
spec:
  rules:
    - name: inject-pod-labels
      match:
        any:
        - resources:
            kinds:
              - Pod
            # Optional: Uncomment and modify the following fields to apply only to specific namespaces
            # namespaces:
            #   - my-project-ns
      mutate:
        patchStrategicMerge:
          metadata:
            labels:
              # The +() syntax adds the label if it doesn't exist, and does not overwrite it if it does
              +(company.com/managed-by): "kyverno"
              +(company.com/environment): "production"

1.2 为 Pod 强制统一的 RestartPolicy

此策略强制要求所有新创建 Pod 的默认 restartPolicyAlways。这对于确保业务容器在异常退出时能够自动重启至关重要。

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: enforce-restart-policy
spec:
  rules:
    - name: set-restart-policy-always
      match:
        any:
        - resources:
            kinds:
              - Pod
      mutate:
        patchStrategicMerge:
          spec:
            # This will forcefully overwrite the restartPolicy to Always, even if the user specifies Never or OnFailure
            restartPolicy: Always

2. 基于 Namespace/Project 的自动化模板配置(Generate)

当创建新的 namespace 或 project 时,Kyverno 的 Generate 规则可以检测到该事件,并自动生成相关的 Kubernetes 资源(如 NetworkPolicy、ConfigMap、Secret、RoleBinding 等)。这相当于一个开箱即用的安全与统一配置模板

2.1 自动注入默认隔离 NetworkPolicy

此策略会在创建新的 namespace 时自动生成默认的 NetworkPolicy。该策略默认拒绝所有入站(Ingress)请求,从而覆盖默认的网络连通性,实现 namespace 之间的网络隔离。

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: generate-default-networkpolicy
  annotations:
    policies.kyverno.io/title: Generate Default NetworkPolicy
    policies.kyverno.io/subject: Namespace, NetworkPolicy
    policies.kyverno.io/description: >-
      Automatically generates a NetworkPolicy that denies all cross-namespace inbound traffic when a new Namespace is created,
      achieving default network isolation between projects.
spec:
  rules:
    - name: generate-deny-all-networkpolicy
      match:
        any:
        - resources:
            kinds:
              - Namespace
      # Exclude specific system namespaces to prevent blocking system components
      exclude:
        any:
        - resources:
            namespaces:
              - kube-system
              - kyverno
              - monitoring
      generate:
        kind: NetworkPolicy
        apiVersion: networking.k8s.io/v1
        name: default-deny-all
        # Use a template variable to get the name of the newly created Namespace
        namespace: "{{request.object.metadata.name}}"
        # synchronize=true means that if this Kyverno policy changes, the generated resources will automatically sync and update
        synchronize: true 
        data:
          metadata:
            labels:
              security.policy/type: "default-deny"
          spec:
            podSelector: {} # An empty selector matches all Pods in the namespace
            policyTypes:
            - Ingress
            # Without specifying Ingress rules (whitelists), all Ingress traffic is denied

2.2 基于模板自动初始化 Project 配置(DBS/安全配额)

此示例演示如何基于 project 属性(例如创建 Namespace 时应用的标签)自动准备一系列底层环境。例如,发放 DBS 连接模板(供 CLI 或应用程序读取)以及默认安全配额(LimitRange)。

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: setup-namespace-dbs-template
spec:
  rules:
    # Rule 1: Automatically generate DBS default configuration for projects with specific labels
    - name: generate-dbs-configmap
      match:
        any:
        - resources:
            kinds:
              - Namespace
            selector:
              matchLabels:
                project-type: database # Triggers when the NS has this Label
      generate:
        kind: ConfigMap
        apiVersion: v1
        name: dbs-default-template
        namespace: "{{request.object.metadata.name}}"
        synchronize: true
        data:
          data:
            # Default DBS configuration for CLI support tools
            dbs-url: "jdbc:mysql://default-db-cluster:3306/db"
            dbs-cli-version: "v1.2.0"
            secure-mode: "true"
            
    # Rule 2: Uniformly generate LimitRange (security limits) for all newly created Namespaces
    - name: generate-default-limitrange
      match:
        any:
        - resources:
            kinds:
              - Namespace
      generate:
        kind: LimitRange
        apiVersion: v1
        name: default-limits
        namespace: "{{request.object.metadata.name}}"
        synchronize: true
        data:
          spec:
            limits:
            - default:
                cpu: 500m
                memory: 512Mi
              defaultRequest:
                cpu: 100m
                memory: 128Mi
              type: Container

总结

  1. Mutate 能力:以非侵入方式修复并补充开发人员提交的 YAML,轻松实现资源级别的标签与状态控制(例如 RestartPolicy)。
  2. Generate 能力:作为声明式的 project 生成器。一旦发生 Namespace 创建事件,Kyverno 就会在后台自动填充安全策略(NetworkPolicy)和依赖模板(ConfigMap、Secret、LimitRange),为 CLI 工具和上层应用提供高度标准化、统一的隔离环境。