All Policies

Time-Bound Policy

Sometimes a policy should be active or inactive based on a time window determined as part of the policy. Whether the policy should come into play should be dependent on that time. This policy illustrates how to time-bound any policy by using preconditions with JMESPath time filters. In this case, the policy enforces that label `foo` be required on all ConfigMaps during the hours of 8am-5pm EST (expressed in UTC). Additional, similar preconditions may be added to perform other time checks, for example a range of days.

Policy Definition

/other/time-bound-policy/time-bound-policy.yaml

 1apiVersion: kyverno.io/v2beta1
 2kind: ClusterPolicy
 3metadata:
 4  name: time-bound-policy
 5  annotations:
 6    policies.kyverno.io/title: Time-Bound Policy
 7    policies.kyverno.io/category: Other
 8    policies.kyverno.io/minversion: 1.9.0
 9    kyverno.io/kyverno-version: 1.9.0
10    kyverno.io/kubernetes-version: "1.24"
11    policies.kyverno.io/subject: ConfigMap
12    policies.kyverno.io/description: >-
13      Sometimes a policy should be active or inactive based on a time window
14      determined as part of the policy. Whether the policy should come into play
15      should be dependent on that time. This policy illustrates how to time-bound
16      any policy by using preconditions with JMESPath time filters. In this case,
17      the policy enforces that label `foo` be required on all ConfigMaps during
18      the hours of 8am-5pm EST (expressed in UTC). Additional, similar preconditions
19      may be added to perform other time checks, for example a range of days.
20spec:
21  validationFailureAction: Audit
22  background: false
23  rules:
24    - name: require-foo-on-configmaps
25      match:
26        any:
27        - resources:
28            kinds:
29            - ConfigMap
30      preconditions:
31        all:
32          # Get the hour of the current time
33        - key: "{{ time_now_utc().time_to_cron(@).split(@,' ') | [1].to_number(@) }}"
34          operator: AnyIn
35          # Only operate during business hours, 8am-5pm EST, in UTC
36          value: 13-22
37      validate:
38        message: "The foo label must be set."
39        pattern:
40          metadata:
41            labels:
42              foo: "?*"