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    pod-policies.kyverno.io/autogen-controllers: none
10    kyverno.io/kyverno-version: 1.6.0
11    policies.kyverno.io/minversion: 1.7.0
12    kyverno.io/kubernetes-version: "1.23"
13    policies.kyverno.io/subject: Pod
14    policies.kyverno.io/description: >-
15      Container images which use metadata such as the LABEL directive in a Dockerfile
16      do not surface this information to apps running within. In some cases, running the image
17      as a container may need access to this information. This policy injects the value of a label
18      set in a Dockerfile named `maintainer` as an environment variable to the corresponding container
19      in the Pod.      
20spec:
21  rules:
22  - name: add-env-maintainer
23    match:
24      any:
25      - resources:
26          kinds:
27          - Pod
28    preconditions:
29      all:
30      - key: "{{request.operation || 'BACKGROUND'}}"
31        operator: NotEquals
32        value: DELETE
33    mutate:
34      foreach:
35      - list: "request.object.spec.containers"
36        context: 
37        - name: maintainer
38          imageRegistry: 
39            reference: "{{ element.image }}"
40            jmesPath: "configData.config.Labels.maintainer || ''"
41        preconditions:
42          all:
43          - key: "{{maintainer}}"
44            operator: NotEquals
45            value: ""
46        patchesJson6902: |-
47          - op: add
48            path: "/spec/containers/{{elementIndex}}/env/-"
49            value:
50              name: MAINTAINER
51              value: "{{maintainer}}"