All Policies

Spread Pods Across Nodes

Deployments to a Kubernetes cluster with multiple availability zones often need to distribute those replicas to align with those zones to ensure site-level failures do not impact availability. This policy matches Deployments with the label `distributed=required` and mutates them to spread Pods across zones.

Policy Definition

/other/spread_pods_across_topology.yaml

 1apiVersion: kyverno.io/v1
 2kind: ClusterPolicy
 3metadata:
 4  name: spread-pods
 5  annotations:
 6    policies.kyverno.io/title: Spread Pods Across Nodes 
 7    policies.kyverno.io/category: Sample
 8    policies.kyverno.io/subject: Deployment, Pod
 9    policies.kyverno.io/description: >-
10      Deployments to a Kubernetes cluster with multiple availability zones often need to
11      distribute those replicas to align with those zones to ensure site-level failures
12      do not impact availability. This policy matches Deployments with the label
13      `distributed=required` and mutates them to spread Pods across zones.      
14spec:
15  rules:
16    - name: spread-pods-across-nodes
17      # Matches any Deployment with the label `distributed=required`
18      match:
19        resources:
20          kinds:
21          - Deployment
22          selector:
23            matchLabels:
24              distributed: required
25      # Mutates the incoming Deployment.
26      mutate:
27        patchStrategicMerge:
28          spec:
29            template:
30              spec:
31                # Adds the topologySpreadConstraints field if non-existent in the request.
32                +(topologySpreadConstraints):
33                - maxSkew: 1
34                  topologyKey: zone
35                  whenUnsatisfiable: DoNotSchedule
36                  labelSelector:
37                    matchLabels:
38                      distributed: required