All Policies

Allowed Annotations in CEL expressions

Rather than creating a deny list of annotations, it may be more useful to invert that list and create an allow list which then denies any others. This policy demonstrates how to allow two annotations with a specific key name of fluxcd.io/ while denying others that do not meet the pattern.

Policy Definition

/other-cel/allowed-annotations/allowed-annotations.yaml

 1apiVersion: kyverno.io/v1
 2kind: ClusterPolicy
 3metadata:
 4  name: allowed-annotations
 5  annotations:
 6    policies.kyverno.io/title: Allowed Annotations in CEL expressions
 7    policies.kyverno.io/category: Other in CEL 
 8    policies.kyverno.io/severity: medium
 9    kyverno.io/kyverno-version: 1.11.0
10    policies.kyverno.io/minversion: 1.11.0
11    kyverno.io/kubernetes-version: "1.26-1.27"
12    policies.kyverno.io/subject: Pod, Annotation
13    policies.kyverno.io/description: >-
14      Rather than creating a deny list of annotations, it may be more useful
15      to invert that list and create an allow list which then denies any others.
16      This policy demonstrates how to allow two annotations with a specific key
17      name of fluxcd.io/ while denying others that do not meet the pattern.
18spec:
19  validationFailureAction: Audit
20  background: true
21  rules:
22  - name: allowed-fluxcd-annotations
23    match:
24      any:
25      - resources:
26          kinds:
27            - Pod
28          operations:
29          - CREATE
30          - UPDATE
31    validate:
32      cel:
33        expressions:
34          - expression: >-
35              object.metadata.?annotations.orValue([]).all(annotation, !annotation.contains('fluxcd.io/') || annotation in ['fluxcd.io/cow', 'fluxcd.io/dog'])
36            message: The only approved FluxCD annotations are `fluxcd.io/cow` and `fluxcd.io/dog`.
37