All Policies

Limit Containers per Pod

Pods can have many different containers which are tightly coupled. It may be desirable to limit the amount of containers that can be in a single Pod to control best practice application or so policy can be applied consistently. This policy checks all Pods to ensure they have no more than four containers.

Policy Definition

/other/limit_containers_per_pod.yaml

 1apiVersion: kyverno.io/v1
 2kind: ClusterPolicy
 3metadata:
 4  name: limit-containers-per-pod
 5  annotations:
 6    policies.kyverno.io/title: Limit Containers per Pod
 7    policies.kyverno.io/category: Sample
 8    policies.kyverno.io/minversion: 1.3.6
 9    policies.kyverno.io/subject: Pod
10    policies.kyverno.io/description: >-
11      Pods can have many different containers which
12      are tightly coupled. It may be desirable to limit the amount of containers that
13      can be in a single Pod to control best practice application or so policy can
14      be applied consistently. This policy checks all Pods to ensure they have
15      no more than four containers.      
16spec:
17  background: false
18  validationFailureAction: audit
19  rules:
20  - name: limit-containers-per-pod-controllers
21    match:
22      resources:
23        kinds:
24        - Deployment
25        - DaemonSet
26        - Job
27        - StatefulSet
28    preconditions:
29      all:
30      - key: "{{request.operation}}"
31        operator: Equal
32        value: CREATE
33    validate:
34      message: "Pods can only have a maximum of 4 containers."
35      deny:
36        conditions:
37          any:
38          - key: "{{request.object.spec.template.spec.containers[] | length(@)}}"
39            operator: GreaterThan
40            value: "4"
41  - name: limit-containers-per-pod-bare
42    match:
43      resources:
44        kinds:
45        - Pod
46    preconditions:
47      all:
48      - key: "{{request.operation}}"
49        operator: Equal
50        value: CREATE
51    validate:
52      message: "Pods can only have a maximum of 4 containers."
53      deny:
54        conditions:
55          any:
56          - key: "{{request.object.spec.containers[] | length(@)}}"
57            operator: GreaterThan
58            value: "4"
59  - name: limit-containers-per-pod-cronjob
60    match:
61      resources:
62        kinds:
63        - CronJob
64    preconditions:
65      all:
66      - key: "{{request.operation}}"
67        operator: Equal
68        value: CREATE
69    validate:
70      message: "Pods can only have a maximum of 4 containers."
71      deny:
72        conditions:
73          any:
74          - key: "{{request.object.spec.jobTemplate.spec.template.spec.containers[] | length(@)}}"
75            operator: GreaterThan
76            value: "4"
77