All Policies

Add Image as Environment Variable

The Kubernetes downward API only has the ability to express so many options as environment variables. The image consumed in a Pod is commonly needed to make the application aware of some logic it must take. This policy takes the value of the `image` field and adds it as an environment variable to Pods.

Policy Definition

/other/add-image-as-env-var/add-image-as-env-var.yaml

 1apiVersion: kyverno.io/v1
 2kind: ClusterPolicy
 3metadata:
 4  name: add-image-as-env-var
 5  annotations:
 6    pod-policies.kyverno.io/autogen-controllers: none
 7    policies.kyverno.io/title: Add Image as Environment Variable
 8    policies.kyverno.io/category: Other
 9    policies.kyverno.io/severity: medium
10    kyverno.io/kyverno-version: 1.10.0-alpha.2
11    kyverno.io/kubernetes-version: "1.26"
12    policies.kyverno.io/subject: Pod
13    policies.kyverno.io/description: >-
14      The Kubernetes downward API only has the ability to express so many
15      options as environment variables. The image consumed in a Pod is commonly
16      needed to make the application aware of some logic it must take. This policy
17      takes the value of the `image` field and adds it as an environment variable
18      to Pods.
19spec:
20  rules:
21  - name: pod-containers-inject-image
22    match:
23      any:
24      - resources:
25          kinds:
26          - Pod
27    mutate:
28      foreach:
29      - list: request.object.spec.containers[]
30        patchesJson6902: |-
31          - op: add
32            path: /spec/containers/{{elementIndex}}/env/-
33            value:
34              name: K8S_IMAGE
35              value: "{{ element.image }}"