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/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` defined
23 all:
24 - key: "{{request.object.spec.template.metadata.labels.app || ''}}"
25 operator: NotEquals
26 value: ""
27 # Mutates the Deployment resource to add fields.
28 mutate:
29 patchStrategicMerge:
30 spec:
31 template:
32 spec:
33 # Add the `affinity`if not already specified.
34 +(affinity):
35 +(podAntiAffinity):
36 +(preferredDuringSchedulingIgnoredDuringExecution):
37 - weight: 1
38 podAffinityTerm:
39 topologyKey: "kubernetes.io/hostname"
40 labelSelector:
41 matchExpressions:
42 - key: app
43 operator: In
44 values:
45 - "{{request.object.spec.template.metadata.labels.app}}"