All Policies

Allowed Label Changes

In some cases, operations teams need a type of limited access to change resources during troubleshooting or outage mitigation. This policy demonstrates how to prevent modification to labels except one with the key `breakglass`. Changing, adding, or deleting any other labels is denied.

Policy Definition

/other/allowed_label_changes/allowed-label-changes.yaml

 1apiVersion: kyverno.io/v1
 2kind: ClusterPolicy
 3metadata:
 4  name: allowed-label-changes
 5  annotations:
 6    pod-policies.kyverno.io/autogen-controllers: none
 7    policies.kyverno.io/title: Allowed Label Changes
 8    policies.kyverno.io/category: Other
 9    policies.kyverno.io/severity: medium
10    kyverno.io/kyverno-version: 1.6.0
11    policies.kyverno.io/minversion: 1.6.0
12    kyverno.io/kubernetes-version: "1.23"
13    policies.kyverno.io/subject: Pod,Label
14    policies.kyverno.io/description: >-
15      In some cases, operations teams need a type of limited access to
16      change resources during troubleshooting or outage mitigation.
17      This policy demonstrates how to prevent modification to labels
18      except one with the key `breakglass`. Changing, adding, or deleting
19      any other labels is denied.      
20spec:
21  validationFailureAction: enforce
22  background: false
23  rules:
24  - name: safe-label
25    match:
26      any:
27      - resources:
28          kinds:
29          - Pod
30          - Deployment
31          - StatefulSet
32          - DaemonSet
33          - Job
34          - CronJob
35    preconditions:
36      all:
37      - key: "{{ request.operation || 'BACKGROUND' }}"
38        operator: Equals
39        value: UPDATE
40    validate:
41      message: "The only label that may be removed or changed is `breakglass`."
42      deny:
43        conditions:
44          any:
45            - key: "{{ request.object.metadata.labels || `{}` |  merge(@, {breakglass:null}) }}"
46              operator: NotEquals
47              value: "{{ request.oldObject.metadata.labels || `{}` |  merge(@, {breakglass:null}) }}"