All Policies

Metadata Matches Regex

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/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
 7    policies.kyverno.io/category: Other
 8    policies.kyverno.io/severity: medium
 9    policies.kyverno.io/subject: Pod, Label
10    policies.kyverno.io/description: >-
11      Rather than a simple check to see if given metadata such as labels and annotations are present,
12      in some cases they need to be present and the values match a specified regular expression. This
13      policy illustrates how to ensure a label with key `corp.org/version` is both present and matches
14      a given regex, in this case ensuring semver is met.      
15spec:
16  validationFailureAction: audit
17  background: false
18  rules:
19  - name: check-for-regex
20    match:
21      any:
22      - resources:
23          kinds:
24          - Pod
25    validate:
26      message: >-
27        The label `corp.org/version` is required and must match the specified regex: ^v[0-9].[0-9].[0-9]$        
28      deny:
29        conditions:
30          all:
31          - key: "{{ regex_match('^v[0-9].[0-9].[0-9]$','{{request.object.metadata.labels.\"corp.org/version\" || 'empty'}}') }}"
32            operator: Equals
33            value: false