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