All Policies

Inject Env Var from Image Label

Container images which use metadata such as the LABEL directive in a Dockerfile do not surface this information to apps running within. In some cases, running the image as a container may need access to this information. This policy injects the value of a label set in a Dockerfile named `maintainer` as an environment variable to the corresponding container in the Pod.

Policy Definition

/other/inject_env_var_from_image_label/inject-env-var-from-image-label.yaml

 1apiVersion: kyverno.io/v1
 2kind: ClusterPolicy
 3metadata:
 4  name: inject-env-var-from-image-label
 5  annotations:
 6    policies.kyverno.io/title: Inject Env Var from Image Label
 7    policies.kyverno.io/category: Other
 8    policies.kyverno.io/severity: medium
 9    kyverno.io/kyverno-version: 1.6.0
10    policies.kyverno.io/minversion: 1.7.0
11    kyverno.io/kubernetes-version: "1.23"
12    policies.kyverno.io/subject: Pod
13    policies.kyverno.io/description: >-
14      Container images which use metadata such as the LABEL directive in a Dockerfile
15      do not surface this information to apps running within. In some cases, running the image
16      as a container may need access to this information. This policy injects the value of a label
17      set in a Dockerfile named `maintainer` as an environment variable to the corresponding container
18      in the Pod.      
19spec:
20  rules:
21  - name: add-env-maintainer
22    match:
23      any:
24      - resources:
25          kinds:
26          - Pod
27    preconditions:
28      all:
29      - key: "{{request.operation || 'BACKGROUND'}}"
30        operator: NotEquals
31        value: DELETE
32    mutate:
33      foreach:
34      - list: "request.object.spec.containers"
35        context: 
36        - name: maintainer
37          imageRegistry: 
38            reference: "{{ element.image }}"
39            jmesPath: "configData.config.Labels.maintainer || ''"
40        preconditions:
41          all:
42          - key: "{{maintainer}}"
43            operator: NotEquals
44            value: ""
45        patchesJson6902: |-
46          - op: add
47            path: "/spec/containers/{{elementIndex}}/env/-"
48            value: {"name":"MAINTAINER","value":"{{maintainer}}"}