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/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/minversion: 1.6.0
10    policies.kyverno.io/description: >-
11      Deployments to a Kubernetes cluster with multiple availability zones often need to
12      distribute those replicas to align with those zones to ensure site-level failures
13      do not impact availability. This policy matches Deployments with the label
14      `distributed=required` and mutates them to spread Pods across zones.
15spec:
16  rules:
17    - name: spread-pods-across-nodes
18      # Matches any Deployment with the label `distributed=required`
19      match:
20        any:
21        - resources:
22            kinds:
23            - Deployment
24            selector:
25              matchLabels:
26                distributed: required
27      # Mutates the incoming Deployment.
28      mutate:
29        patchStrategicMerge:
30          spec:
31            template:
32              spec:
33                # Adds the topologySpreadConstraints field if non-existent in the request.
34                +(topologySpreadConstraints):
35                - maxSkew: 1
36                  topologyKey: zone
37                  whenUnsatisfiable: DoNotSchedule
38                  labelSelector:
39                    matchLabels:
40                      distributed: required