All Policies

Add Pod Anti-Affinity

Applications may involve multiple replicas of the same Pod for availability as well as scale purposes, yet Kubernetes does not by default provide a solution for availability. This policy sets a Pod anti-affinity configuration on Deployments which contain an `app` label if it is not already present.

Policy Definition

/other/create-pod-antiaffinity/create-pod-antiaffinity.yaml

 1apiVersion: kyverno.io/v1
 2kind: ClusterPolicy
 3metadata:
 4  name: insert-pod-antiaffinity
 5  annotations:
 6    policies.kyverno.io/title: Add Pod Anti-Affinity
 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      Applications may involve multiple replicas of the same Pod for availability as well as scale
12      purposes, yet Kubernetes does not by default provide a solution for availability. This policy
13      sets a Pod anti-affinity configuration on Deployments which contain an `app` label if it is
14      not already present.      
15spec:
16  rules:
17    - name: insert-pod-antiaffinity
18      match:
19        any:
20        - resources:
21            kinds:
22              - Deployment
23      preconditions:
24        # This precondition selects Pods with the label `app` defined
25        all:
26        - key: "{{request.object.spec.template.metadata.labels.app || ''}}"
27          operator: NotEquals
28          value: ""
29      # Mutates the Deployment resource to add fields.
30      mutate:
31        patchStrategicMerge:
32          spec:
33            template:
34              spec:
35                # Add the `affinity`if not already specified.
36                +(affinity):
37                  +(podAntiAffinity):
38                    +(preferredDuringSchedulingIgnoredDuringExecution):
39                      - weight: 1
40                        podAffinityTerm:
41                          topologyKey: "kubernetes.io/hostname"
42                          labelSelector:
43                            matchExpressions:
44                            - key: app
45                              operator: In
46                              values:
47                              - "{{request.object.spec.template.metadata.labels.app}}"