All Policies

Require Kubecost Labels in CEL expressions

Kubecost can use labels assigned to Pods in order to track and display cost allocation in a granular way. These labels, which can be customized, can be used to organize and group workloads in different ways. This policy requires that the labels `owner`, `team`, `department`, `app`, and `env` are all defined on Pods. With Kyverno autogen enabled (absence of the annotation `pod-policies.kyverno.io/autogen-controllers=none`), these labels will also be required for all Pod controllers.

Policy Definition

/kubecost-cel/require-kubecost-labels/require-kubecost-labels.yaml

 1apiVersion: kyverno.io/v1
 2kind: ClusterPolicy
 3metadata:
 4  name: require-kubecost-labels
 5  annotations:
 6    policies.kyverno.io/title: Require Kubecost Labels in CEL expressions
 7    policies.kyverno.io/category: Kubecost in CEL 
 8    policies.kyverno.io/severity: medium
 9    policies.kyverno.io/subject: Pod, Label
10    kyverno.io/kyverno-version: 1.11.0
11    kyverno.io/kubernetes-version: "1.26-1.27"
12    policies.kyverno.io/description: >-
13      Kubecost can use labels assigned to Pods in order to track and display
14      cost allocation in a granular way. These labels, which can be customized, can be used
15      to organize and group workloads in different ways. This policy requires that the labels
16      `owner`, `team`, `department`, `app`, and `env` are all defined on Pods. With Kyverno
17      autogen enabled (absence of the annotation `pod-policies.kyverno.io/autogen-controllers=none`),
18      these labels will also be required for all Pod controllers.
19spec:
20  validationFailureAction: Audit
21  background: true
22  rules:
23  - name: require-labels
24    match:
25      any:
26      - resources:
27          kinds:
28          - Pod
29          operations:
30          - CREATE
31          - UPDATE
32    validate:
33      cel:  
34        expressions:
35          - expression: >-
36              object.metadata.?labels.?owner.orValue('') != '' && 
37              object.metadata.?labels.?team.orValue('') != '' &&
38              object.metadata.?labels.?department.orValue('') != '' &&
39              object.metadata.?labels.?app.orValue('') != '' &&
40              object.metadata.?labels.?env.orValue('') != ''
41            message: "The Kubecost labels `owner`, `team`, `department`, `app`, and `env` are all required for Pods."