All Policies
Exclude Namespaces Dynamically
It's common where policy lookups need to consider a mapping to many possible values rather than a static mapping. This is a sample which demonstrates how to dynamically look up an allow list of Namespaces from a ConfigMap where the ConfigMap stores an array of strings. This policy validates that any Pods created outside of the list of Namespaces have the label `foo` applied.
Policy Definition
/other/exclude_namespaces_dynamically.yaml
1apiVersion: kyverno.io/v1
2kind: ClusterPolicy
3metadata:
4 name: exclude-namespaces-example
5 annotations:
6 policies.kyverno.io/title: Exclude Namespaces Dynamically
7 policies.kyverno.io/category: Sample
8 policies.kyverno.io/severity: medium
9 policies.kyverno.io/subject: Namespace, Pod
10 policies.kyverno.io/description: >-
11 It's common where policy lookups need to consider a mapping to many possible values rather than a
12 static mapping. This is a sample which demonstrates how to dynamically look up an allow list of Namespaces from a ConfigMap
13 where the ConfigMap stores an array of strings. This policy validates that any Pods created
14 outside of the list of Namespaces have the label `foo` applied.
15spec:
16 validationFailureAction: audit
17 background: false
18 rules:
19 - name: exclude-namespaces-dynamically
20 context:
21 - name: namespacefilters
22 # The source ConfigMap should contain an array of strings in either YAML block scalars
23 # (Kyverno 1.3.5+) or JSON-encoded format.
24 configMap:
25 name: namespace-filters
26 namespace: default
27 match:
28 resources:
29 kinds:
30 - Pod
31 preconditions:
32 - key: "{{request.object.metadata.namespace}}"
33 operator: NotIn
34 value: "{{namespacefilters.data.exclude}}"
35 validate:
36 message: >
37 Creating Pods in the {{request.object.metadata.namespace}} namespace,
38 which is not in the excluded list of namespaces {{ namespacefilters.data.exclude }},
39 is forbidden unless it carries the label `foo`.
40 pattern:
41 metadata:
42 labels:
43 foo: "*"