All Policies

Require NetworkPolicy

NetworkPolicy is used to control Pod-to-Pod communication and is a good practice to ensure only authorized Pods can send/receive traffic. This policy checks incoming Deployments to ensure they have a matching, preexisting NetworkPolicy.

Policy Definition

/other/require-netpol/require-netpol.yaml

 1apiVersion: kyverno.io/v1
 2kind: ClusterPolicy
 3metadata:
 4  name: require-network-policy
 5  annotations:
 6    policies.kyverno.io/title: Require NetworkPolicy
 7    policies.kyverno.io/category: Sample
 8    policies.kyverno.io/minversion: 1.6.0
 9    kyverno.io/kyverno-version: 1.6.2
10    kyverno.io/kubernetes-version: "1.23"
11    policies.kyverno.io/subject: Deployment, NetworkPolicy
12    policies.kyverno.io/description: >-
13      NetworkPolicy is used to control Pod-to-Pod communication
14      and is a good practice to ensure only authorized Pods can send/receive
15      traffic. This policy checks incoming Deployments to ensure
16      they have a matching, preexisting NetworkPolicy.      
17spec:
18  validationFailureAction: audit
19  background: false
20  rules:
21  - name: require-network-policy
22    match:
23      any:
24      - resources:
25          kinds:
26          - Deployment
27    preconditions:
28      any:
29      - key: "{{request.operation || 'BACKGROUND'}}"
30        operator: Equals
31        value: CREATE
32    context:
33    - name: policies_count
34      apiCall:
35        urlPath: "/apis/networking.k8s.io/v1/namespaces/{{request.namespace}}/networkpolicies"
36        jmesPath: "items[?label_match(spec.podSelector.matchLabels, `{{request.object.spec.template.metadata.labels}}`)] | length(@)"
37    validate:
38      message: "Every Deployment requires a matching NetworkPolicy."
39      deny:
40        conditions:
41          any:
42          - key: "{{policies_count}}"
43            operator: LessThan
44            value: 1