All Policies

Metadata Matches Regex in CEL expressions

Rather than a simple check to see if given metadata such as labels and annotations are present, in some cases they need to be present and the values match a specified regular expression. This policy illustrates how to ensure a label with key `corp.org/version` is both present and matches a given regex, in this case ensuring semver is met.

Policy Definition

/other-cel/metadata-match-regex/metadata-match-regex.yaml

 1apiVersion: kyverno.io/v1
 2kind: ClusterPolicy
 3metadata:
 4  name: metadata-match-regex
 5  annotations:
 6    policies.kyverno.io/title: Metadata Matches Regex in CEL expressions
 7    policies.kyverno.io/category: Other in CEL 
 8    policies.kyverno.io/severity: medium
 9    policies.kyverno.io/subject: Pod, Label
10    policies.kyverno.io/minversion: 1.11.0
11    kyverno.io/kubernetes-version: "1.26-1.27"
12    policies.kyverno.io/description: >-
13      Rather than a simple check to see if given metadata such as labels and annotations are present,
14      in some cases they need to be present and the values match a specified regular expression. This
15      policy illustrates how to ensure a label with key `corp.org/version` is both present and matches
16      a given regex, in this case ensuring semver is met.
17spec:
18  validationFailureAction: Audit
19  background: false
20  rules:
21  - name: check-for-regex
22    match:
23      any:
24      - resources:
25          kinds:
26          - Pod
27          operations:
28          - CREATE
29          - UPDATE
30    validate:
31      cel:
32        expressions:
33          - expression: >-
34              object.metadata.?labels[?'corp.org/version'].orValue('default').matches('^v[0-9].[0-9].[0-9]$')
35            message: >-
36              The label `corp.org/version` is required and must match the specified regex: ^v[0-9].[0-9].[0-9]$